Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
232624b1 | 4 | | CiviCRM version 4.4 | |
6a488035 TO |
5 | +--------------------------------------------------------------------+ |
6 | | Copyright CiviCRM LLC (c) 2004-2013 | | |
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 | +--------------------------------------------------------------------+ | |
26 | */ | |
27 | ||
28 | /** | |
29 | * | |
30 | * @package CRM | |
31 | * @copyright CiviCRM LLC (c) 2004-2013 | |
32 | * $Id$ | |
33 | * | |
34 | */ | |
35 | class CRM_Dedupe_Merger { | |
6a488035 TO |
36 | |
37 | // FIXME: consider creating a common structure with cidRefs() and eidRefs() | |
38 | // FIXME: the sub-pages references by the URLs should | |
39 | // be loaded dynamically on the merge form instead | |
40 | static function relTables() { | |
41 | static $relTables; | |
42 | ||
43 | $config = CRM_Core_Config::singleton(); | |
44 | if ($config->userSystem->is_drupal) { | |
45 | $userRecordUrl = CRM_Utils_System::url('user/%ufid'); | |
46 | $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid')); | |
47 | } | |
48 | elseif ($config->userFramework == 'Joomla') { | |
49 | $userRecordUrl = $config->userFrameworkVersion > 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'; | |
50 | $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid')); | |
51 | } | |
52 | ||
53 | if (!$relTables) { | |
54 | $relTables = array( | |
55 | 'rel_table_contributions' => array( | |
56 | 'title' => ts('Contributions'), | |
57 | 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'), | |
58 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'), | |
59 | ), | |
60 | 'rel_table_contribution_page' => array( | |
61 | 'title' => ts('Contribution Pages'), | |
62 | 'tables' => array('civicrm_contribution_page'), | |
63 | 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'), | |
64 | ), | |
65 | 'rel_table_memberships' => array( | |
66 | 'title' => ts('Memberships'), | |
67 | 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'), | |
68 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'), | |
69 | ), | |
70 | 'rel_table_participants' => array( | |
71 | 'title' => ts('Participants'), | |
72 | 'tables' => array('civicrm_participant'), | |
73 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'), | |
74 | ), | |
75 | 'rel_table_events' => array( | |
76 | 'title' => ts('Events'), | |
77 | 'tables' => array('civicrm_event'), | |
78 | 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'), | |
79 | ), | |
80 | 'rel_table_activities' => array( | |
81 | 'title' => ts('Activities'), | |
91da6cd5 | 82 | 'tables' => array('civicrm_activity', 'civicrm_activity_contact'), |
6a488035 TO |
83 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'), |
84 | ), | |
85 | 'rel_table_relationships' => array( | |
86 | 'title' => ts('Relationships'), | |
87 | 'tables' => array('civicrm_relationship'), | |
88 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'), | |
89 | ), | |
90 | 'rel_table_custom_groups' => array( | |
91 | 'title' => ts('Custom Groups'), | |
92 | 'tables' => array('civicrm_custom_group'), | |
93 | 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'), | |
94 | ), | |
95 | 'rel_table_uf_groups' => array( | |
96 | 'title' => ts('Profiles'), | |
97 | 'tables' => array('civicrm_uf_group'), | |
98 | 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'), | |
99 | ), | |
100 | 'rel_table_groups' => array( | |
101 | 'title' => ts('Groups'), | |
102 | 'tables' => array('civicrm_group_contact'), | |
103 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'), | |
104 | ), | |
105 | 'rel_table_notes' => array( | |
106 | 'title' => ts('Notes'), | |
107 | 'tables' => array('civicrm_note'), | |
108 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'), | |
109 | ), | |
110 | 'rel_table_tags' => array( | |
111 | 'title' => ts('Tags'), | |
112 | 'tables' => array('civicrm_entity_tag'), | |
113 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'), | |
114 | ), | |
115 | 'rel_table_mailings' => array( | |
116 | 'title' => ts('Mailings'), | |
117 | 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'), | |
118 | 'url' => CRM_Utils_System::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'), | |
119 | ), | |
120 | 'rel_table_cases' => array( | |
121 | 'title' => ts('Cases'), | |
122 | 'tables' => array('civicrm_case_contact'), | |
123 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'), | |
124 | ), | |
125 | 'rel_table_grants' => array( | |
126 | 'title' => ts('Grants'), | |
127 | 'tables' => array('civicrm_grant'), | |
128 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'), | |
129 | ), | |
130 | 'rel_table_pcp' => array( | |
131 | 'title' => ts('PCPs'), | |
132 | 'tables' => array('civicrm_pcp'), | |
133 | 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'), | |
134 | ), | |
135 | 'rel_table_pledges' => array( | |
136 | 'title' => ts('Pledges'), | |
137 | 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'), | |
138 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'), | |
139 | ), | |
140 | 'rel_table_users' => array( | |
141 | 'title' => $title, | |
142 | 'tables' => array('civicrm_uf_match'), | |
143 | 'url' => $userRecordUrl, | |
144 | ), | |
145 | ); | |
146 | ||
76c53278 CW |
147 | $relTables += self::getMultiValueCustomSets('relTables'); |
148 | ||
6a488035 TO |
149 | // Allow hook_civicrm_merge() to adjust $relTables |
150 | CRM_Utils_Hook::merge('relTables', $relTables); | |
151 | } | |
152 | return $relTables; | |
153 | } | |
154 | ||
155 | /** | |
156 | * Returns the related tables groups for which a contact has any info entered | |
157 | */ | |
158 | static function getActiveRelTables($cid) { | |
159 | $cid = (int) $cid; | |
160 | $groups = array(); | |
161 | ||
162 | $relTables = self::relTables(); | |
163 | $cidRefs = self::cidRefs(); | |
164 | $eidRefs = self::eidRefs(); | |
165 | foreach ($relTables as $group => $params) { | |
166 | $sqls = array(); | |
167 | foreach ($params['tables'] as $table) { | |
168 | if (isset($cidRefs[$table])) { | |
169 | foreach ($cidRefs[$table] as $field) { | |
170 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid"; | |
171 | } | |
172 | } | |
173 | if (isset($eidRefs[$table])) { | |
174 | foreach ($eidRefs[$table] as $entityTable => $entityId) { | |
175 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'"; | |
176 | } | |
177 | } | |
178 | foreach ($sqls as $sql) { | |
179 | if (CRM_Core_DAO::singleValueQuery($sql) > 0) { | |
180 | $groups[] = $group; | |
181 | } | |
182 | } | |
183 | } | |
184 | } | |
185 | return array_unique($groups); | |
186 | } | |
187 | ||
188 | /** | |
189 | * Return tables and their fields referencing civicrm_contact.contact_id explicitely | |
190 | */ | |
191 | static function cidRefs() { | |
192 | static $cidRefs; | |
193 | if (!$cidRefs) { | |
194 | // FIXME: this should be generated dynamically from the schema's | |
195 | // foreign keys referencing civicrm_contact(id) | |
196 | $cidRefs = array( | |
197 | 'civicrm_acl_cache' => array('contact_id'), | |
91da6cd5 | 198 | 'civicrm_activity_contact' => array('contact_id'), |
6a488035 TO |
199 | 'civicrm_case_contact' => array('contact_id'), |
200 | 'civicrm_contact' => array('primary_contact_id'), | |
b2ee367a | 201 | 'civicrm_contribution' => array('contact_id'), |
6a488035 TO |
202 | 'civicrm_contribution_page' => array('created_id'), |
203 | 'civicrm_contribution_recur' => array('contact_id'), | |
204 | 'civicrm_contribution_soft' => array('contact_id'), | |
205 | 'civicrm_custom_group' => array('created_id'), | |
206 | 'civicrm_entity_tag' => array('entity_id'), | |
207 | 'civicrm_event' => array('created_id'), | |
208 | 'civicrm_grant' => array('contact_id'), | |
209 | 'civicrm_group_contact' => array('contact_id'), | |
210 | 'civicrm_group_organization' => array('organization_id'), | |
211 | 'civicrm_log' => array('modified_id'), | |
212 | 'civicrm_mailing' => array('created_id', 'scheduled_id'), | |
213 | 'civicrm_mailing_event_queue' => array('contact_id'), | |
214 | 'civicrm_mailing_event_subscribe' => array('contact_id'), | |
215 | 'civicrm_membership' => array('contact_id'), | |
216 | 'civicrm_membership_log' => array('modified_id'), | |
217 | 'civicrm_membership_type' => array('member_of_contact_id'), | |
218 | 'civicrm_note' => array('contact_id'), | |
219 | 'civicrm_participant' => array('contact_id'), | |
220 | 'civicrm_pcp' => array('contact_id'), | |
221 | 'civicrm_relationship' => array('contact_id_a', 'contact_id_b'), | |
222 | 'civicrm_uf_match' => array('contact_id'), | |
223 | 'civicrm_uf_group' => array('created_id'), | |
224 | 'civicrm_pledge' => array('contact_id'), | |
225 | ); | |
226 | ||
76c53278 CW |
227 | $cidRefs += self::getMultiValueCustomSets('cidRefs'); |
228 | ||
6a488035 TO |
229 | // Add ContactReference custom fields CRM-9561 |
230 | $sql = "SELECT cg.table_name, cf.column_name | |
231 | FROM civicrm_custom_group cg, civicrm_custom_field cf | |
232 | WHERE cg.id = cf.custom_group_id AND cf.data_type = 'ContactReference'"; | |
233 | $dao = CRM_Core_DAO::executeQuery($sql); | |
234 | while ($dao->fetch()) { | |
235 | $cidRefs[$dao->table_name][] = $dao->column_name; | |
236 | } | |
237 | $dao->free(); | |
238 | ||
239 | // Allow hook_civicrm_merge() to adjust $cidRefs | |
240 | CRM_Utils_Hook::merge('cidRefs', $cidRefs); | |
241 | } | |
242 | return $cidRefs; | |
243 | } | |
244 | ||
245 | /** | |
246 | * Return tables and their fields referencing civicrm_contact.contact_id with entity_id | |
247 | */ | |
248 | static function eidRefs() { | |
249 | static $eidRefs; | |
250 | if (!$eidRefs) { | |
251 | // FIXME: this should be generated dynamically from the schema | |
252 | // tables that reference contacts with entity_{id,table} | |
253 | $eidRefs = array( | |
254 | 'civicrm_acl' => array('entity_table' => 'entity_id'), | |
255 | 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'), | |
256 | 'civicrm_entity_file' => array('entity_table' => 'entity_id'), | |
257 | 'civicrm_log' => array('entity_table' => 'entity_id'), | |
258 | 'civicrm_mailing_group' => array('entity_table' => 'entity_id'), | |
259 | 'civicrm_note' => array('entity_table' => 'entity_id'), | |
6a488035 TO |
260 | ); |
261 | ||
262 | // Allow hook_civicrm_merge() to adjust $eidRefs | |
263 | CRM_Utils_Hook::merge('eidRefs', $eidRefs); | |
264 | } | |
265 | return $eidRefs; | |
266 | } | |
267 | ||
76c53278 CW |
268 | /** |
269 | * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc. | |
270 | * @param string $request 'relTables' or 'cidRefs' | |
271 | * @see CRM-13836 | |
272 | */ | |
273 | static function getMultiValueCustomSets($request) { | |
274 | static $data = NULL; | |
275 | if ($data === NULL) { | |
276 | $data = array( | |
277 | 'relTables' => array(), | |
278 | 'cidRefs' => array(), | |
279 | ); | |
280 | $result = civicrm_api3('custom_group', 'get', array( | |
281 | 'is_multiple' => 1, | |
282 | 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')), | |
283 | 'return' => array('id', 'title', 'table_name', 'style'), | |
284 | )); | |
285 | foreach($result['values'] as $custom) { | |
286 | $data['cidRefs'][$custom['table_name']] = array('entity_id'); | |
287 | $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : ''; | |
288 | $data['relTables']['rel_table_custom_' . $custom['id']] = array( | |
289 | 'title' => $custom['title'], | |
290 | 'tables' => array($custom['table_name']), | |
291 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix), | |
292 | ); | |
293 | } | |
294 | } | |
295 | return $data[$request]; | |
296 | } | |
297 | ||
6a488035 TO |
298 | /** |
299 | * Tables which require custom processing should declare functions to call here. | |
300 | * Doing so will override normal processing. | |
301 | */ | |
302 | static function cpTables() { | |
303 | static $tables; | |
304 | if (!$tables) { | |
305 | $tables = array( | |
306 | 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'), | |
307 | 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'), | |
308 | // Empty array == do nothing - this table is handled by mergeGroupContact | |
309 | 'civicrm_subscription_history' => array(), | |
310 | 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'), | |
311 | ); | |
312 | } | |
313 | return $tables; | |
314 | } | |
315 | ||
316 | /** | |
317 | * return payment related table. | |
318 | */ | |
319 | static function paymentTables() { | |
320 | static $tables; | |
321 | if (!$tables) { | |
322 | $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant'); | |
323 | } | |
324 | ||
325 | return $tables; | |
326 | } | |
327 | ||
328 | /** | |
329 | * return payment update Query. | |
330 | */ | |
331 | static function paymentSql($tableName, $mainContactId, $otherContactId) { | |
332 | $sqls = array(); | |
333 | if (!$tableName || !$mainContactId || !$otherContactId) { | |
334 | return $sqls; | |
335 | } | |
336 | ||
337 | $paymentTables = self::paymentTables(); | |
338 | if (!in_array($tableName, $paymentTables)) { | |
339 | return $sqls; | |
340 | } | |
341 | ||
342 | switch ($tableName) { | |
343 | case 'civicrm_pledge': | |
344 | $sqls[] = " | |
345 | UPDATE IGNORE civicrm_contribution contribution | |
346 | INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id ) | |
347 | INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id ) | |
348 | SET contribution.contact_id = $mainContactId | |
349 | WHERE pledge.contact_id = $otherContactId"; | |
350 | break; | |
351 | ||
352 | case 'civicrm_membership': | |
353 | $sqls[] = " | |
354 | UPDATE IGNORE civicrm_contribution contribution | |
355 | INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id ) | |
356 | INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id ) | |
357 | SET contribution.contact_id = $mainContactId | |
358 | WHERE membership.contact_id = $otherContactId"; | |
359 | break; | |
360 | ||
361 | case 'civicrm_participant': | |
362 | $sqls[] = " | |
363 | UPDATE IGNORE civicrm_contribution contribution | |
364 | INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id ) | |
365 | INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id ) | |
366 | SET contribution.contact_id = $mainContactId | |
367 | WHERE participant.contact_id = $otherContactId"; | |
368 | break; | |
369 | } | |
370 | ||
371 | return $sqls; | |
372 | } | |
373 | ||
374 | static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') { | |
375 | $sqls = array(); | |
376 | if (!$tableName || !$mainId || !$otherId) { | |
377 | return $sqls; | |
378 | } | |
379 | ||
380 | ||
381 | switch ($tableName) { | |
382 | case 'civicrm_membership': | |
383 | if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) | |
384 | break; | |
385 | if ($mode == 'add') { | |
386 | $sqls[] = " | |
387 | DELETE membership1.* FROM civicrm_membership membership1 | |
388 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id | |
389 | AND membership1.contact_id = {$mainId} | |
390 | AND membership2.contact_id = {$otherId} "; | |
391 | } | |
392 | if ($mode == 'payment') { | |
393 | $sqls[] = " | |
394 | DELETE contribution.* FROM civicrm_contribution contribution | |
395 | INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id | |
396 | INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id | |
397 | AND membership1.contact_id = {$mainId} | |
398 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id | |
399 | AND membership2.contact_id = {$otherId}"; | |
400 | } | |
401 | break; | |
402 | ||
403 | case 'civicrm_uf_match': | |
404 | // normal queries won't work for uf_match since that will lead to violation of unique constraint, | |
405 | // failing to meet intended result. Therefore we introduce this additonal query: | |
406 | $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}"; | |
407 | break; | |
408 | } | |
409 | ||
410 | return $sqls; | |
411 | } | |
412 | ||
413 | /** | |
414 | * Based on the provided two contact_ids and a set of tables, move the | |
415 | * belongings of the other contact to the main one. | |
416 | * | |
417 | * @static | |
418 | */ | |
419 | static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) { | |
420 | $cidRefs = self::cidRefs(); | |
421 | $eidRefs = self::eidRefs(); | |
422 | $cpTables = self::cpTables(); | |
423 | $paymentTables = self::paymentTables(); | |
ada104d5 | 424 | $membershipMerge = FALSE; // CRM-12695 |
6a488035 TO |
425 | |
426 | $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs)); | |
427 | if ($tables !== FALSE) { | |
428 | // if there are specific tables, sanitize the list | |
429 | $affected = array_unique(array_intersect($affected, $tables)); | |
430 | } | |
431 | else { | |
432 | // if there aren't any specific tables, don't affect the ones handled by relTables() | |
433 | $relTables = self::relTables(); | |
434 | $handled = array(); | |
435 | foreach ($relTables as $params) { | |
436 | $handled = array_merge($handled, $params['tables']); | |
437 | } | |
438 | $affected = array_diff($affected, $handled); | |
ada104d5 AW |
439 | /** |
440 | * CRM-12695 | |
441 | * Set $membershipMerge flag only once | |
442 | * while doing contact related migration | |
443 | * to call addMembershipToRealtedContacts() | |
444 | * function only once. | |
445 | * Since the current function (moveContactBelongings) is called twice | |
446 | * with & without parameters $tables & $tableOperations | |
447 | */ | |
448 | // retrieve main contact's related table(s) | |
449 | $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); | |
450 | // check if membership table exists in main contact's related table(s) | |
451 | if (in_array('rel_table_memberships', $activeMainRelTables)) { | |
452 | $membershipMerge = TRUE; // set membership flag - CRM-12695 | |
453 | } | |
6a488035 TO |
454 | } |
455 | ||
456 | $mainId = (int) $mainId; | |
457 | $otherId = (int) $otherId; | |
458 | ||
459 | $sqls = array(); | |
460 | foreach ($affected as $table) { | |
461 | // Call custom processing function for objects that require it | |
462 | if (isset($cpTables[$table])) { | |
463 | foreach ($cpTables[$table] as $className => $fnName) { | |
464 | $className::$fnName($mainId, $otherId, $sqls); | |
465 | } | |
466 | // Skip normal processing | |
467 | continue; | |
468 | } | |
b3fdbf3d | 469 | |
6a488035 TO |
470 | // use UPDATE IGNORE + DELETE query pair to skip on situations when |
471 | // there's a UNIQUE restriction on ($field, some_other_field) pair | |
472 | if (isset($cidRefs[$table])) { | |
473 | foreach ($cidRefs[$table] as $field) { | |
474 | // carry related contributions CRM-5359 | |
475 | if (in_array($table, $paymentTables)) { | |
476 | $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment'); | |
477 | $sqls = array_merge($sqls, $payOprSqls); | |
478 | ||
479 | $paymentSqls = self::paymentSql($table, $mainId, $otherId); | |
480 | $sqls = array_merge($sqls, $paymentSqls); | |
481 | } | |
482 | ||
483 | $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations); | |
484 | $sqls = array_merge($sqls, $preOperationSqls); | |
485 | ||
486 | $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId"; | |
487 | $sqls[] = "DELETE FROM $table WHERE $field = $otherId"; | |
488 | } | |
489 | } | |
490 | if (isset($eidRefs[$table])) { | |
491 | foreach ($eidRefs[$table] as $entityTable => $entityId) { | |
492 | $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; | |
493 | $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; | |
494 | } | |
495 | } | |
496 | } | |
497 | ||
498 | // Allow hook_civicrm_merge() to add SQL statements for the merge operation. | |
499 | CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables); | |
500 | ||
501 | // call the SQL queries in one transaction | |
502 | $transaction = new CRM_Core_Transaction(); | |
503 | foreach ($sqls as $sql) { | |
504 | CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE); | |
505 | } | |
ada104d5 AW |
506 | // CRM-12695 |
507 | if ($membershipMerge) { | |
508 | // call to function adding membership to related contacts | |
509 | CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId); | |
510 | } | |
6a488035 TO |
511 | $transaction->commit(); |
512 | } | |
513 | ||
514 | /** | |
515 | * Find differences between contacts. | |
b3fdbf3d | 516 | * |
6a488035 TO |
517 | * @param array $main contact details |
518 | * @param array $other contact details | |
519 | * | |
520 | * @static | |
521 | */ | |
522 | static function findDifferences($main, $other) { | |
523 | $result = array( | |
524 | 'contact' => array(), | |
525 | 'custom' => array(), | |
526 | ); | |
16254ae1 | 527 | foreach (self::getContactFields() as $validField) { |
6a488035 TO |
528 | if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) { |
529 | $result['contact'][] = $validField; | |
530 | } | |
531 | } | |
532 | ||
533 | $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']); | |
534 | $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']); | |
535 | $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs))); | |
536 | foreach ($keys as $key) { | |
76c53278 CW |
537 | // Exclude multi-value fields CRM-13836 |
538 | if (strpos($key, '_')) { | |
539 | continue; | |
540 | } | |
6a488035 TO |
541 | $key1 = CRM_Utils_Array::value($key, $mainEvs); |
542 | $key2 = CRM_Utils_Array::value($key, $otherEvs); | |
543 | if ($key1 != $key2) { | |
544 | $result['custom'][] = $key; | |
545 | } | |
546 | } | |
547 | return $result; | |
548 | } | |
549 | ||
550 | /** | |
551 | * Function to batch merge a set of contacts based on rule-group and group. | |
552 | * | |
553 | * @param int $rgid rule group id | |
554 | * @param int $gid group id | |
555 | * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed. | |
556 | * Generally used with batch-merge. | |
557 | * @param string $mode helps decide how to behave when there are conflicts. | |
558 | * A 'safe' value skips the merge if there are any un-resolved conflicts. | |
559 | * Does a force merge otherwise. | |
560 | * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete. | |
561 | * | |
562 | * | |
563 | * @static | |
564 | * @access public | |
565 | */ | |
566 | static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) { | |
567 | $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type'); | |
568 | $cacheKeyString = "merge {$contactType}"; | |
569 | $cacheKeyString .= $rgid ? "_{$rgid}" : '_0'; | |
570 | $cacheKeyString .= $gid ? "_{$gid}" : '_0'; | |
571 | $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND | |
572 | pn.entity_id2 = de.contact_id2 )"; | |
573 | ||
574 | $limit = $redirectForPerformance ? 75 : 1; | |
575 | $where = "de.id IS NULL LIMIT {$limit}"; | |
576 | ||
577 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where); | |
578 | if (empty($dupePairs) && !$redirectForPerformance) { | |
579 | // If we haven't found any dupes, probably cache is empty. | |
580 | // Try filling cache and give another try. | |
581 | CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString); | |
582 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where); | |
583 | } | |
584 | ||
585 | $cacheParams = array( | |
586 | 'cache_key_string' => $cacheKeyString, | |
587 | 'join' => $join, | |
588 | 'where' => $where, | |
589 | ); | |
590 | return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance); | |
591 | } | |
592 | ||
593 | /** | |
594 | * Function to merge given set of contacts. Performs core operation. | |
595 | * | |
596 | * @param array $dupePairs set of pair of contacts for whom merge is to be done. | |
597 | * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed. | |
598 | * Generally used with batch-merge. | |
599 | * @param string $mode helps decide how to behave when there are conflicts. | |
600 | * A 'safe' value skips the merge if there are any un-resolved conflicts. | |
601 | * Does a force merge otherwise (aggressive mode). | |
602 | * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete. | |
603 | * | |
604 | * | |
605 | * @static | |
606 | * @access public | |
607 | */ | |
608 | static function merge($dupePairs = array( | |
609 | ), $cacheParams = array(), $mode = 'safe', | |
610 | $autoFlip = TRUE, $redirectForPerformance = FALSE | |
611 | ) { | |
612 | $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams); | |
613 | $resultStats = array('merged' => array(), 'skipped' => array()); | |
614 | ||
615 | // we don't want dupe caching to get reset after every-merge, and therefore set the | |
616 | // doNotResetCache flag | |
617 | $config = CRM_Core_Config::singleton(); | |
618 | $config->doNotResetCache = 1; | |
619 | ||
620 | while (!empty($dupePairs)) { | |
621 | foreach ($dupePairs as $dupes) { | |
622 | $mainId = $dupes['dstID']; | |
623 | $otherId = $dupes['srcID']; | |
624 | // make sure that $mainId is the one with lower id number | |
625 | if ($autoFlip && ($mainId > $otherId)) { | |
626 | $mainId = $dupes['srcID']; | |
627 | $otherId = $dupes['dstID']; | |
628 | } | |
629 | if (!$mainId || !$otherId) { | |
630 | // return error | |
631 | return FALSE; | |
632 | } | |
633 | ||
634 | // Generate var $migrationInfo. The variable structure is exactly same as | |
635 | // $formValues submitted during a UI merge for a pair of contacts. | |
636 | $rowsElementsAndInfo = &CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId); | |
637 | ||
638 | $migrationInfo = &$rowsElementsAndInfo['migration_info']; | |
639 | ||
640 | // add additional details that we might need to resolve conflicts | |
641 | $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details']; | |
642 | $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details']; | |
643 | $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block']; | |
644 | $migrationInfo['rows'] = &$rowsElementsAndInfo['rows']; | |
645 | ||
646 | // go ahead with merge if there is no conflict | |
647 | if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode)) { | |
648 | CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo); | |
649 | $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId); | |
650 | } | |
651 | else { | |
652 | $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId); | |
653 | } | |
654 | ||
655 | // delete entry from PrevNextCache table so we don't consider the pair next time | |
656 | // pair may have been flipped, so make sure we delete using both orders | |
657 | CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString); | |
658 | CRM_Core_BAO_PrevNextCache::deletePair($otherId, $mainId, $cacheKeyString); | |
659 | ||
660 | CRM_Core_DAO::freeResult(); | |
661 | unset($rowsElementsAndInfo, $migrationInfo); | |
662 | } | |
663 | ||
664 | if ($cacheKeyString && !$redirectForPerformance) { | |
665 | // retrieve next pair of dupes | |
666 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, | |
667 | $cacheParams['join'], | |
668 | $cacheParams['where'] | |
669 | ); | |
670 | } | |
671 | else { | |
672 | // do not proceed. Terminate the loop | |
673 | unset($dupePairs); | |
674 | } | |
675 | } | |
676 | return $resultStats; | |
677 | } | |
678 | ||
679 | /** | |
680 | * A function which uses various rules / algorithms for choosing which contact to bias to | |
681 | * when there's a conflict (to handle "gotchas"). Plus the safest route to merge. | |
682 | * | |
683 | * @param int $mainId main contact with whom merge has to happen | |
684 | * @param int $otherId duplicate contact which would be deleted after merge operation | |
685 | * @param array $migrationInfo array of information about which elements to merge. | |
686 | * @param string $mode helps decide how to behave when there are conflicts. | |
687 | * A 'safe' value skips the merge if there are any un-resolved conflicts. | |
688 | * Does a force merge otherwise (aggressive mode). | |
689 | * | |
690 | * @static | |
691 | * @access public | |
692 | */ | |
693 | static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') { | |
694 | $conflicts = array(); | |
695 | $migrationData = array( | |
696 | 'old_migration_info' => $migrationInfo, | |
697 | 'mode' => $mode, | |
698 | ); | |
b2b0530a | 699 | $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
6a488035 TO |
700 | |
701 | foreach ($migrationInfo as $key => $val) { | |
702 | if ($val === "null") { | |
703 | // Rule: no overwriting with empty values in any mode | |
704 | unset($migrationInfo[$key]); | |
705 | continue; | |
706 | } | |
16254ae1 | 707 | elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or |
6a488035 TO |
708 | substr($key, 0, 12) == 'move_custom_' |
709 | ) and $val != NULL) { | |
710 | // Rule: if both main-contact has other-contact, let $mode decide if to merge a | |
711 | // particular field or not | |
712 | if (!empty($migrationInfo['rows'][$key]['main'])) { | |
713 | // if main also has a value its a conflict | |
714 | if ($mode == 'safe') { | |
715 | // note it down & lets wait for response from the hook. | |
716 | // For no response skip this merge | |
717 | $conflicts[$key] = NULL; | |
718 | } | |
719 | elseif ($mode == 'aggressive') { | |
720 | // let the main-field be overwritten | |
721 | continue; | |
722 | } | |
723 | } | |
724 | } | |
725 | elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) { | |
726 | $locField = explode('_', $key); | |
727 | $fieldName = $locField[2]; | |
728 | $fieldCount = $locField[3]; | |
729 | ||
730 | // Rule: resolve address conflict if any - | |
731 | if ($fieldName == 'address') { | |
732 | $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId']; | |
a7488080 | 733 | if (!empty($migrationInfo['main_loc_address']) && |
6a488035 TO |
734 | array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) { |
735 | // main loc already has some address for the loc-type. Its a overwrite situation. | |
736 | ||
737 | // look for next available loc-type | |
738 | $newTypeId = NULL; | |
739 | foreach ($allLocationTypes as $typeId => $typeLabel) { | |
740 | if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) { | |
741 | $newTypeId = $typeId; | |
742 | } | |
743 | } | |
744 | if ($newTypeId) { | |
745 | // try insert address at new available loc-type | |
746 | $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId; | |
747 | } | |
748 | elseif ($mode == 'safe') { | |
749 | // note it down & lets wait for response from the hook. | |
750 | // For no response skip this merge | |
751 | $conflicts[$key] = NULL; | |
752 | } | |
753 | elseif ($mode == 'aggressive') { | |
754 | // let the loc-type-id be same as that of other-contact & go ahead | |
755 | // with merge assuming aggressive mode | |
756 | continue; | |
757 | } | |
758 | } | |
759 | } | |
760 | elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) { | |
761 | // for loc blocks other than address like email, phone .. if values are same no point in merging | |
762 | // and adding redundant value | |
763 | unset($migrationInfo[$key]); | |
764 | } | |
765 | } | |
766 | } | |
767 | ||
768 | // A hook to implement other algorithms for choosing which contact to bias to when | |
769 | // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here | |
770 | // merge happens with new values filled in here. For a particular field / row not to be merged | |
771 | // field should be unset from fields_in_conflict. | |
772 | $migrationData['fields_in_conflict'] = $conflicts; | |
773 | CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId); | |
774 | $conflicts = $migrationData['fields_in_conflict']; | |
775 | ||
776 | if (!empty($conflicts)) { | |
777 | foreach ($conflicts as $key => $val) { | |
778 | if ($val === NULL and $mode == 'safe') { | |
779 | // un-resolved conflicts still present. Lets skip this merge. | |
780 | return TRUE; | |
781 | } | |
782 | else { | |
783 | // copy over the resolved values | |
784 | $migrationInfo[$key] = $val; | |
785 | } | |
786 | } | |
787 | } | |
788 | return FALSE; | |
789 | } | |
790 | ||
791 | /** | |
792 | * A function to build an array of information required by merge function and the merge UI. | |
793 | * | |
794 | * @param int $mainId main contact with whom merge has to happen | |
795 | * @param int $otherId duplicate contact which would be deleted after merge operation | |
796 | * | |
797 | * @static | |
798 | * @access public | |
799 | */ | |
800 | static function getRowsElementsAndInfo($mainId, $otherId) { | |
801 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; | |
802 | ||
803 | // Fetch contacts | |
804 | foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { | |
16254ae1 | 805 | $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields())); |
6a488035 TO |
806 | $result = civicrm_api('contact', 'get', $params); |
807 | ||
808 | if (empty($result['values'][$cid]['contact_type'])) { | |
809 | return FALSE; | |
810 | } | |
811 | $$moniker = $result['values'][$cid]; | |
812 | } | |
813 | ||
814 | static $fields = array(); | |
815 | if (empty($fields)) { | |
816 | $fields = CRM_Contact_DAO_Contact::fields(); | |
817 | CRM_Core_DAO::freeResult(); | |
818 | } | |
819 | ||
820 | // FIXME: there must be a better way | |
821 | foreach (array('main', 'other') as $moniker) { | |
822 | $contact = &$$moniker; | |
823 | $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact); | |
824 | $value = empty($preferred_communication_method) ? array() : $preferred_communication_method; | |
825 | $specialValues[$moniker] = array( | |
826 | 'preferred_communication_method' => $value, | |
827 | ); | |
828 | ||
a7488080 | 829 | if (!empty($contact['preferred_communication_method'])){ |
6a488035 | 830 | // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct |
b3fdbf3d DL |
831 | $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? |
832 | implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : | |
6a488035 TO |
833 | $specialValues[$moniker]['preferred_communication_method']; |
834 | $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR; | |
835 | } | |
836 | $names = array( | |
837 | 'preferred_communication_method' => | |
838 | array( | |
839 | 'newName' => 'preferred_communication_method_display', | |
840 | 'groupName' => 'preferred_communication_method', | |
841 | ), | |
842 | ); | |
843 | CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names); | |
844 | } | |
845 | ||
846 | static $optionValueFields = array(); | |
847 | if (empty($optionValueFields)) { | |
848 | $optionValueFields = CRM_Core_OptionValue::getFields(); | |
849 | } | |
850 | foreach ($optionValueFields as $field => $params) { | |
851 | $fields[$field]['title'] = $params['title']; | |
852 | } | |
853 | ||
854 | $diffs = self::findDifferences($main, $other); | |
855 | ||
856 | $rows = $elements = $relTableElements = $migrationInfo = array(); | |
857 | ||
858 | foreach ($diffs['contact'] as $field) { | |
859 | foreach (array('main', 'other') as $moniker) { | |
860 | $contact = &$$moniker; | |
861 | $value = CRM_Utils_Array::value($field, $contact); | |
862 | if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) { | |
863 | $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR; | |
864 | } | |
865 | $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value; | |
a7488080 | 866 | if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) { |
6a488035 TO |
867 | if ($value) { |
868 | $value = str_replace('-', '', $value); | |
869 | $label = CRM_Utils_Date::customFormat($label); | |
870 | } | |
871 | else { | |
872 | $value = "null"; | |
873 | } | |
874 | } | |
a7488080 | 875 | elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { |
6a488035 TO |
876 | if ($label === '0') { |
877 | $label = ts('[ ]'); | |
878 | } | |
879 | if ($label === '1') { | |
880 | $label = ts('[x]'); | |
881 | } | |
00f3da2e BS |
882 | } |
883 | elseif ($field == 'individual_prefix' || $field == 'prefix_id') { | |
884 | $label = CRM_Utils_Array::value('individual_prefix', $contact); | |
6a488035 TO |
885 | $value = CRM_Utils_Array::value('prefix_id', $contact); |
886 | $field = 'prefix_id'; | |
00f3da2e BS |
887 | } |
888 | elseif ($field == 'individual_suffix' || $field == 'suffix_id') { | |
889 | $label = CRM_Utils_Array::value('individual_suffix', $contact); | |
6a488035 TO |
890 | $value = CRM_Utils_Array::value('suffix_id', $contact); |
891 | $field = 'suffix_id'; | |
892 | } | |
893 | $rows["move_$field"][$moniker] = $label; | |
894 | if ($moniker == 'other') { | |
895 | if ($value === NULL) { | |
896 | $value = 'null'; | |
897 | } | |
898 | if ($value === 0 or $value === '0') { | |
899 | $value = $qfZeroBug; | |
900 | } | |
8cc574cf | 901 | if (is_array($value) && empty($value[1])) { |
6a488035 TO |
902 | $value[1] = NULL; |
903 | } | |
904 | $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value); | |
905 | $migrationInfo["move_$field"] = $value; | |
906 | } | |
907 | } | |
908 | $rows["move_$field"]['title'] = $fields[$field]['title']; | |
909 | } | |
910 | ||
911 | // handle location blocks. | |
912 | $locationBlocks = array('email', 'phone', 'address'); | |
913 | $locations = array(); | |
914 | ||
915 | foreach ($locationBlocks as $block) { | |
916 | foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { | |
917 | $cnt = 1; | |
918 | $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3)); | |
919 | $count = $values['count']; | |
920 | if ($count) { | |
921 | if ($count > $cnt) { | |
922 | foreach ($values['values'] as $value) { | |
923 | if ($block == 'address') { | |
924 | CRM_Core_BAO_Address::fixAddress($value); | |
925 | $display = CRM_Utils_Address::format($value); | |
926 | $locations[$moniker][$block][$cnt] = $value; | |
927 | $locations[$moniker][$block][$cnt]['display'] = $display; | |
928 | } | |
929 | else { | |
930 | $locations[$moniker][$block][$cnt] = $value; | |
931 | } | |
932 | ||
933 | $cnt++; | |
934 | } | |
935 | } | |
936 | else { | |
937 | $id = $values['id']; | |
938 | if ($block == 'address') { | |
939 | CRM_Core_BAO_Address::fixAddress($values['values'][$id]); | |
940 | $display = CRM_Utils_Address::format($values['values'][$id]); | |
941 | $locations[$moniker][$block][$cnt] = $values['values'][$id]; | |
942 | $locations[$moniker][$block][$cnt]['display'] = $display; | |
943 | } | |
944 | else { | |
945 | $locations[$moniker][$block][$cnt] = $values['values'][$id]; | |
946 | } | |
947 | } | |
948 | } | |
949 | } | |
950 | } | |
951 | ||
b2b0530a | 952 | $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
6a488035 TO |
953 | |
954 | $mainLocBlock = $locBlockIds = array(); | |
955 | $locBlockIds['main'] = $locBlockIds['other'] = array(); | |
956 | foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) { | |
957 | $name = strtolower($block); | |
958 | foreach (array('main', 'other') as $moniker) { | |
959 | $locIndex = CRM_Utils_Array::value($moniker, $locations); | |
960 | $blockValue = CRM_Utils_Array::value($name, $locIndex, array()); | |
961 | if (empty($blockValue)) { | |
962 | $locValue[$moniker][$name] = 0; | |
963 | $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array(); | |
964 | } | |
965 | else { | |
966 | $locValue[$moniker][$name] = TRUE; | |
967 | foreach ($blockValue as $count => $blkValues) { | |
968 | $fldName = $name; | |
969 | $locTypeId = $blkValues['location_type_id']; | |
970 | if ($name == 'im') { | |
971 | $fldName = 'name'; | |
972 | } | |
973 | if ($name == 'address') { | |
974 | $fldName = 'display'; | |
975 | } | |
976 | $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, | |
977 | $blkValues | |
978 | ); | |
979 | $locTypes[$moniker][$name][$count] = $locTypeId; | |
980 | if ($moniker == 'main' && in_array($name, $locationBlocks)) { | |
981 | $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array::value($fldName, | |
982 | $blkValues | |
983 | ); | |
984 | $locBlockIds['main'][$name][$locTypeId] = $blkValues['id']; | |
985 | } | |
986 | else { | |
987 | $locBlockIds[$moniker][$name][$count] = $blkValues['id']; | |
988 | } | |
989 | } | |
990 | } | |
991 | } | |
992 | ||
993 | if ($locValue['other'][$name] != 0) { | |
994 | foreach ($locLabel['other'][$name] as $count => $value) { | |
995 | $locTypeId = $locTypes['other'][$name][$count]; | |
996 | $rows["move_location_{$name}_$count"]['other'] = $value; | |
997 | $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count, | |
998 | $locLabel['main'][$name] | |
999 | ); | |
1000 | $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3', | |
1001 | array( | |
1002 | 1 => $block, | |
1003 | 2 => $count, | |
1004 | 3 => $allLocationTypes[$locTypeId] | |
1005 | ) | |
1006 | ); | |
1007 | ||
1008 | $elements[] = array('advcheckbox', "move_location_{$name}_{$count}"); | |
1009 | $migrationInfo["move_location_{$name}_{$count}"] = 1; | |
1010 | ||
1011 | // make sure default location type is always on top | |
1012 | $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId); | |
1013 | $locTypeValues = $allLocationTypes; | |
1014 | $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]); | |
1015 | unset($locTypeValues[$mainLocTypeId]); | |
1016 | ||
1017 | // keep 1-1 mapping for address - location type. | |
1018 | $js = NULL; | |
1019 | if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) { | |
1020 | $js = array('onChange' => "mergeBlock('$name', this, $count );"); | |
1021 | } | |
1022 | $elements[] = array( | |
1023 | 'select', "location[{$name}][$count][locTypeId]", NULL, | |
1024 | $defaultLocType + $locTypeValues, $js, | |
1025 | ); | |
1026 | // keep location-type-id same as that of other-contact | |
1027 | $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId; | |
1028 | ||
1029 | if ($name != 'address') { | |
1030 | $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new')); | |
1031 | // always use add operation | |
1032 | $migrationInfo['location'][$name][$count]['operation'] = 1; | |
1033 | } | |
1034 | } | |
1035 | } | |
1036 | } | |
1037 | ||
1038 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info | |
1039 | $config = CRM_Core_Config::singleton(); | |
1040 | $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); | |
1041 | $mainUser = NULL; | |
1042 | if ($mainUfId) { | |
1043 | // d6 compatible | |
1044 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { | |
1045 | $mainUser = user_load($mainUfId); | |
1046 | } | |
1047 | elseif ($config->userFramework == 'Joomla') { | |
1048 | $mainUser = JFactory::getUser($mainUfId); | |
1049 | } | |
1050 | } | |
1051 | $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); | |
1052 | $otherUser = NULL; | |
1053 | if ($otherUfId) { | |
1054 | // d6 compatible | |
1055 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { | |
1056 | $otherUser = user_load($otherUfId); | |
1057 | } | |
1058 | elseif ($config->userFramework == 'Joomla') { | |
1059 | $otherUser = JFactory::getUser($otherUfId); | |
1060 | } | |
1061 | } | |
1062 | ||
1063 | $relTables = CRM_Dedupe_Merger::relTables(); | |
1064 | $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); | |
1065 | $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); | |
1066 | foreach ($relTables as $name => $null) { | |
1067 | if (!in_array($name, $activeRelTables) && | |
1068 | !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables)) | |
1069 | ) { | |
1070 | unset($relTables[$name]); | |
1071 | continue; | |
1072 | } | |
1073 | ||
1074 | $relTableElements[] = array('checkbox', "move_$name"); | |
1075 | $migrationInfo["move_$name"] = 1; | |
1076 | ||
1077 | $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); | |
1078 | $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); | |
1079 | if ($name == 'rel_table_users') { | |
1080 | $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); | |
1081 | $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); | |
1082 | $find = array('$ufid', '$ufname'); | |
1083 | if ($mainUser) { | |
1084 | $replace = array($mainUfId, $mainUser->name); | |
1085 | $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); | |
1086 | } | |
1087 | if ($otherUser) { | |
1088 | $replace = array($otherUfId, $otherUser->name); | |
1089 | $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); | |
1090 | } | |
1091 | } | |
1092 | if ($name == 'rel_table_memberships') { | |
1093 | $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new')); | |
1094 | $migrationInfo["operation"]["move_{$name}"]['add'] = 1; | |
1095 | } | |
1096 | } | |
1097 | foreach ($relTables as $name => $null) { | |
1098 | $relTables["move_$name"] = $relTables[$name]; | |
1099 | unset($relTables[$name]); | |
1100 | } | |
1101 | ||
1102 | // handle custom fields | |
1103 | $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, | |
1104 | CRM_Utils_Array::value('contact_sub_type', $main) | |
1105 | ); | |
1106 | $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, | |
1107 | CRM_Utils_Array::value('contact_sub_type', $other) | |
1108 | ); | |
1109 | CRM_Core_DAO::freeResult(); | |
1110 | ||
1111 | foreach ($otherTree as $gid => $group) { | |
1112 | $foundField = FALSE; | |
1113 | if (!isset($group['fields'])) { | |
1114 | continue; | |
1115 | } | |
1116 | ||
1117 | foreach ($group['fields'] as $fid => $field) { | |
1118 | if (in_array($fid, $diffs['custom'])) { | |
1119 | if (!$foundField) { | |
1120 | $rows["custom_group_$gid"]['title'] = $group['title']; | |
1121 | $foundField = TRUE; | |
1122 | } | |
a7488080 | 1123 | if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { |
6a488035 TO |
1124 | foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
1125 | $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, | |
1126 | $field, TRUE | |
1127 | ); | |
1128 | } | |
1129 | } | |
1130 | $value = "null"; | |
a7488080 | 1131 | if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { |
6a488035 TO |
1132 | foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
1133 | $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, | |
1134 | $field, TRUE | |
1135 | ); | |
1136 | if ($values['data'] === 0 || $values['data'] === '0') { | |
1137 | $values['data'] = $qfZeroBug; | |
1138 | } | |
1139 | $value = ($values['data']) ? $values['data'] : $value; | |
1140 | } | |
1141 | } | |
1142 | $rows["move_custom_$fid"]['title'] = $field['label']; | |
1143 | ||
1144 | $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value); | |
1145 | $migrationInfo["move_custom_$fid"] = $value; | |
1146 | } | |
1147 | } | |
1148 | } | |
1149 | $result = array( | |
1150 | 'rows' => $rows, | |
1151 | 'elements' => $elements, | |
1152 | 'rel_table_elements' => $relTableElements, | |
1153 | 'main_loc_block' => $mainLocBlock, | |
1154 | 'rel_tables' => $relTables, | |
1155 | 'main_details' => $main, | |
1156 | 'other_details' => $other, | |
1157 | 'migration_info' => $migrationInfo, | |
1158 | ); | |
1159 | ||
1160 | $result['main_details']['loc_block_ids'] = $locBlockIds['main']; | |
1161 | $result['other_details']['loc_block_ids'] = $locBlockIds['other']; | |
1162 | ||
1163 | return $result; | |
1164 | } | |
1165 | ||
1166 | /** | |
1167 | * Based on the provided two contact_ids and a set of tables, move the belongings of the | |
1168 | * other contact to the main one - be it Location / CustomFields or Contact .. related info. | |
1169 | * A superset of moveContactBelongings() function. | |
1170 | * | |
1171 | * @param int $mainId main contact with whom merge has to happen | |
1172 | * @param int $otherId duplicate contact which would be deleted after merge operation | |
1173 | * | |
1174 | * @static | |
1175 | * @access public | |
1176 | */ | |
1177 | static function moveAllBelongings($mainId, $otherId, $migrationInfo) { | |
1178 | if (empty($migrationInfo)) { | |
1179 | return FALSE; | |
1180 | } | |
1181 | ||
1182 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; | |
1183 | $relTables = CRM_Dedupe_Merger::relTables(); | |
1184 | $moveTables = $locBlocks = $tableOperations = array(); | |
1185 | foreach ($migrationInfo as $key => $value) { | |
1186 | if ($value == $qfZeroBug) { | |
1187 | $value = '0'; | |
1188 | } | |
16254ae1 | 1189 | if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or |
6a488035 TO |
1190 | substr($key, 0, 12) == 'move_custom_' |
1191 | ) and $value != NULL) { | |
1192 | $submitted[substr($key, 5)] = $value; | |
1193 | } | |
1194 | elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) { | |
1195 | $locField = explode('_', $key); | |
1196 | $fieldName = $locField[2]; | |
1197 | $fieldCount = $locField[3]; | |
1198 | $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]); | |
1199 | // default operation is overwrite. | |
1200 | if (!$operation) { | |
1201 | $operation = 2; | |
1202 | } | |
1203 | ||
1204 | $locBlocks[$fieldName][$fieldCount]['operation'] = $operation; | |
1205 | $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]); | |
1206 | } | |
1207 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') { | |
1208 | $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); | |
1209 | if (array_key_exists('operation', $migrationInfo)) { | |
1210 | foreach ($relTables[substr($key, 5)]['tables'] as $table) { | |
1211 | if (array_key_exists($key, $migrationInfo['operation'])) { | |
1212 | $tableOperations[$table] = $migrationInfo['operation'][$key]; | |
1213 | } | |
1214 | } | |
1215 | } | |
1216 | } | |
1217 | } | |
1218 | ||
1219 | ||
1220 | // **** Do location related migration: | |
1221 | if (!empty($locBlocks)) { | |
1222 | $locComponent = array( | |
1223 | 'email' => 'Email', | |
1224 | 'phone' => 'Phone', | |
1225 | 'im' => 'IM', | |
1226 | 'openid' => 'OpenID', | |
1227 | 'address' => 'Address', | |
1228 | ); | |
1229 | ||
1230 | $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1)); | |
1231 | $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1)); | |
1232 | ||
1233 | foreach ($locBlocks as $name => $block) { | |
1234 | if (!is_array($block) || CRM_Utils_System::isNull($block)) { | |
1235 | continue; | |
1236 | } | |
1237 | $daoName = 'CRM_Core_DAO_' . $locComponent[$name]; | |
1238 | $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL; | |
1239 | $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL; | |
1240 | ||
1241 | foreach ($block as $blkCount => $values) { | |
1242 | $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1); | |
1243 | $operation = CRM_Utils_Array::value('operation', $values, 2); | |
1244 | $otherBlockId = CRM_Utils_Array::value($blkCount, | |
1245 | $migrationInfo['other_details']['loc_block_ids'][$name] | |
1246 | ); | |
1247 | ||
1248 | // keep 1-1 mapping for address - loc type. | |
1249 | $idKey = $blkCount; | |
1250 | if (array_key_exists($name, $locComponent)) { | |
1251 | $idKey = $locTypeId; | |
1252 | } | |
1253 | ||
1254 | if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) { | |
1255 | $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]); | |
1256 | } | |
1257 | ||
1258 | if (!$otherBlockId) { | |
1259 | continue; | |
1260 | } | |
1261 | ||
1262 | // for the block which belongs to other-contact, link the contact to main-contact | |
1263 | $otherBlockDAO = new $daoName(); | |
1264 | $otherBlockDAO->id = $otherBlockId; | |
1265 | $otherBlockDAO->contact_id = $mainId; | |
1266 | $otherBlockDAO->location_type_id = $locTypeId; | |
1267 | ||
1268 | // if main contact already has primary & billing, set the flags to 0. | |
1269 | if ($primaryDAOId) { | |
1270 | $otherBlockDAO->is_primary = 0; | |
1271 | } | |
1272 | if ($billingDAOId) { | |
1273 | $otherBlockDAO->is_billing = 0; | |
1274 | } | |
1275 | ||
1276 | // overwrite - need to delete block which belongs to main-contact. | |
1277 | if ($mainBlockId && ($operation == 2)) { | |
1278 | $deleteDAO = new $daoName(); | |
1279 | $deleteDAO->id = $mainBlockId; | |
1280 | $deleteDAO->find(TRUE); | |
1281 | ||
1282 | // if we about to delete a primary / billing block, set the flags for new block | |
1283 | // that we going to assign to main-contact | |
1284 | if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) { | |
1285 | $otherBlockDAO->is_primary = 1; | |
1286 | } | |
1287 | if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) { | |
1288 | $otherBlockDAO->is_billing = 1; | |
1289 | } | |
1290 | ||
1291 | $deleteDAO->delete(); | |
1292 | $deleteDAO->free(); | |
1293 | } | |
1294 | ||
1295 | $otherBlockDAO->update(); | |
1296 | $otherBlockDAO->free(); | |
1297 | } | |
1298 | } | |
1299 | } | |
1300 | ||
1301 | // **** Do tables related migrations | |
1302 | if (!empty($moveTables)) { | |
1303 | CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations); | |
1304 | unset($moveTables, $tableOperations); | |
1305 | } | |
1306 | ||
1307 | // **** Do contact related migrations | |
1308 | CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId); | |
1309 | ||
1310 | // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact() | |
1311 | $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender'); | |
1312 | $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix'); | |
1313 | $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix'); | |
aa62b355 | 1314 | $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style'); |
6a488035 TO |
1315 | $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee'); |
1316 | $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting'); | |
1317 | $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting'); | |
1318 | CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE); | |
1319 | ||
1320 | // fix custom fields so they're edible by createProfileContact() | |
1321 | static $treeCache = array(); | |
1322 | if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) { | |
1323 | $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], | |
1324 | CRM_Core_DAO::$_nullObject, NULL, -1 | |
1325 | ); | |
1326 | } | |
1327 | $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']]; | |
1328 | ||
1329 | $cFields = array(); | |
1330 | foreach ($cgTree as $key => $group) { | |
1331 | if (!isset($group['fields'])) { | |
1332 | continue; | |
1333 | } | |
1334 | foreach ($group['fields'] as $fid => $field) { | |
1335 | $cFields[$fid]['attributes'] = $field; | |
1336 | } | |
1337 | } | |
1338 | ||
1339 | if (!isset($submitted)) { | |
1340 | $submitted = array(); | |
1341 | } | |
1342 | foreach ($submitted as $key => $value) { | |
1343 | if (substr($key, 0, 7) == 'custom_') { | |
1344 | $fid = (int) substr($key, 7); | |
1345 | $htmlType = $cFields[$fid]['attributes']['html_type']; | |
1346 | switch ($htmlType) { | |
1347 | case 'File': | |
1348 | $customFiles[] = $fid; | |
1349 | unset($submitted["custom_$fid"]); | |
1350 | break; | |
1351 | ||
1352 | case 'Select Country': | |
1353 | case 'Select State/Province': | |
1354 | $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields); | |
1355 | break; | |
1356 | ||
1357 | case 'CheckBox': | |
1358 | case 'AdvMulti-Select': | |
1359 | case 'Multi-Select': | |
1360 | case 'Multi-Select Country': | |
1361 | case 'Multi-Select State/Province': | |
1362 | // Merge values from both contacts for multivalue fields, CRM-4385 | |
1363 | // get the existing custom values from db. | |
1364 | $customParams = array('entityID' => $mainId, $key => TRUE); | |
1365 | $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams); | |
a7488080 | 1366 | if (!empty($customfieldValues[$key])) { |
6a488035 TO |
1367 | $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]); |
1368 | if (is_array($existingValue) && !empty($existingValue)) { | |
1369 | $mergeValue = $submmtedCustomValue = array(); | |
1370 | if ($value) { | |
1371 | $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
1372 | } | |
1373 | ||
1374 | //hack to remove null and duplicate values from array. | |
1375 | foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) { | |
1376 | if ($v != '' && !in_array($v, $mergeValue)) { | |
1377 | $mergeValue[] = $v; | |
1378 | } | |
1379 | } | |
1380 | ||
1381 | //keep state and country as array format. | |
1382 | //for checkbox and m-select format w/ VALUE_SEPARATOR | |
1383 | if (in_array($htmlType, array( | |
1384 | 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) { | |
1385 | $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, | |
1386 | $mergeValue | |
1387 | ) . CRM_Core_DAO::VALUE_SEPARATOR; | |
1388 | } | |
1389 | else { | |
1390 | $submitted[$key] = $mergeValue; | |
1391 | } | |
1392 | } | |
1393 | } | |
1394 | elseif (in_array($htmlType, array( | |
1395 | 'Multi-Select Country', 'Multi-Select State/Province'))) { | |
1396 | //we require submitted values should be in array format | |
1397 | if ($value) { | |
1398 | $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
1399 | //hack to remove null values from array. | |
1400 | $mergeValue = array(); | |
1401 | foreach ($mergeValueArray as $k => $v) { | |
1402 | if ($v != '') { | |
1403 | $mergeValue[] = $v; | |
1404 | } | |
1405 | } | |
1406 | $submitted[$key] = $mergeValue; | |
1407 | } | |
1408 | } | |
1409 | break; | |
1410 | ||
1411 | default: | |
1412 | break; | |
1413 | } | |
1414 | } | |
1415 | } | |
1416 | ||
1417 | // **** Do file custom fields related migrations | |
1418 | // FIXME: move this someplace else (one of the BAOs) after discussing | |
b3fdbf3d | 1419 | // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually, |
6a488035 TO |
1420 | // like, delete a file... |
1421 | ||
1422 | if (!isset($customFiles)) { | |
1423 | $customFiles = array(); | |
1424 | } | |
1425 | foreach ($customFiles as $customId) { | |
1426 | list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId); | |
1427 | ||
1428 | // get the contact_id -> file_id mapping | |
1429 | $fileIds = array(); | |
1430 | $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})"; | |
1431 | $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); | |
1432 | while ($dao->fetch()) { | |
1433 | $fileIds[$dao->entity_id] = $dao->file_id; | |
1434 | } | |
1435 | $dao->free(); | |
1436 | ||
1437 | // delete the main contact's file | |
1438 | if (!empty($fileIds[$mainId])) { | |
b3fdbf3d | 1439 | CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId); |
6a488035 TO |
1440 | } |
1441 | ||
1442 | // move the other contact's file to main contact | |
1443 | //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record | |
1444 | if ( CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) { | |
1445 | $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}"; | |
1446 | } | |
1447 | else { | |
1448 | $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )"; | |
1449 | } | |
1450 | CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); | |
1451 | ||
1452 | if ( CRM_Core_DAO::singleValueQuery(" | |
1453 | SELECT id | |
1454 | FROM civicrm_entity_file | |
1455 | WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) { | |
1456 | $sql = " | |
1457 | UPDATE civicrm_entity_file | |
1458 | SET entity_id = {$mainId} | |
1459 | WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}"; | |
1460 | } | |
1461 | else { | |
1462 | $sql = " | |
1463 | INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id ) | |
1464 | VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )"; | |
1465 | } | |
1466 | CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray); | |
1467 | } | |
1468 | ||
1469 | // move view only custom fields CRM-5362 | |
1470 | $viewOnlyCustomFields = array(); | |
1471 | foreach ($submitted as $key => $value) { | |
1472 | $fid = (int) substr($key, 7); | |
8cc574cf | 1473 | if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) { |
6a488035 TO |
1474 | $viewOnlyCustomFields[$key] = $value; |
1475 | } | |
1476 | } | |
1477 | ||
1478 | // special case to set values for view only, CRM-5362 | |
1479 | if (!empty($viewOnlyCustomFields)) { | |
1480 | $viewOnlyCustomFields['entityID'] = $mainId; | |
1481 | CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields); | |
1482 | } | |
1483 | ||
1484 | // **** Delete other contact & update prev-next caching | |
1485 | $otherParams = array( | |
1486 | 'contact_id' => $otherId, | |
1487 | 'id' => $otherId, | |
1488 | 'version' => 3, | |
1489 | ); | |
1490 | if (CRM_Core_Permission::check('merge duplicate contacts') && | |
1491 | CRM_Core_Permission::check('delete contacts') | |
1492 | ) { | |
1493 | // if ext id is submitted then set it null for contact to be deleted | |
a7488080 | 1494 | if (!empty($submitted['external_identifier'])) { |
6a488035 TO |
1495 | $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}"; |
1496 | CRM_Core_DAO::executeQuery($query); | |
1497 | } | |
1498 | ||
1499 | civicrm_api('contact', 'delete', $otherParams); | |
1500 | CRM_Core_BAO_PrevNextCache::deleteItem($otherId); | |
1501 | } | |
1502 | // FIXME: else part | |
1503 | /* else { */ | |
1504 | ||
1505 | /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */ | |
1506 | ||
1507 | /* } */ | |
1508 | ||
1509 | ||
1510 | // **** Update contact related info for the main contact | |
1511 | if (!empty($submitted)) { | |
1512 | $submitted['contact_id'] = $mainId; | |
1513 | ||
1514 | //update current employer field | |
1515 | if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) { | |
1516 | if (!CRM_Utils_System::isNull($currentEmloyerId)) { | |
1517 | $submitted['current_employer'] = $submitted['current_employer_id']; | |
1518 | } else { | |
1519 | $submitted['current_employer'] = ''; | |
1520 | } | |
1521 | unset($submitted['current_employer_id']); | |
1522 | } | |
1523 | ||
00f3da2e BS |
1524 | //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name |
1525 | if ( !isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id']) ) { | |
1526 | $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id']; | |
1527 | } | |
1528 | if ( !isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id']) ) { | |
1529 | $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id']; | |
1530 | } | |
1531 | ||
6a488035 TO |
1532 | CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId); |
1533 | unset($submitted); | |
1534 | } | |
1535 | ||
1536 | return TRUE; | |
1537 | } | |
16254ae1 ARW |
1538 | |
1539 | /** | |
1540 | * @return array of field names which will be compared, so everything except ID. | |
1541 | */ | |
1542 | static function getContactFields() { | |
1543 | $contactFields = CRM_Contact_DAO_Contact::fields(); | |
b857bab2 RN |
1544 | $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date', |
1545 | 'primary_contact_id', 'sort_name', 'user_unique_id'); | |
bdd7870e RN |
1546 | foreach ($contactFields as $field => $value) { |
1547 | if (in_array($field, $invalidFields)) { | |
1548 | unset($contactFields[$field]); | |
1549 | } | |
1550 | } | |
16254ae1 ARW |
1551 | return array_keys($contactFields); |
1552 | } | |
ada104d5 AW |
1553 | |
1554 | /** | |
1555 | * Added for CRM-12695 | |
1556 | * Based on the contactId provided | |
1557 | * add/update membership(s) to related contacts | |
1558 | * | |
1559 | * @param contactId | |
1560 | */ | |
1561 | static function addMembershipToRealtedContacts($contactID) { | |
1562 | $dao = new CRM_Member_DAO_Membership(); | |
1563 | $dao->contact_id = $contactID; | |
1564 | $dao->is_test = 0; | |
1565 | $dao->find(); | |
1566 | ||
1567 | //checks membership of contact itself | |
1568 | while ($dao->fetch()) { | |
1569 | $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id'); | |
1570 | if ($relationshipTypeId) { | |
1571 | $membershipParams = array( | |
1572 | 'id' => $dao->id, | |
1573 | 'contact_id' => $dao->contact_id, | |
1574 | 'membership_type_id' => $dao->membership_type_id, | |
1575 | 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date), | |
1576 | 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), | |
1577 | 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), | |
1578 | 'source' => $dao->source, | |
1579 | 'status_id' => $dao->status_id | |
1580 | ); | |
1581 | // create/update membership(s) for related contact(s) | |
1582 | CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao); | |
1583 | } // end of if relationshipTypeId | |
1584 | } | |
1585 | } | |
6a488035 TO |
1586 | } |
1587 |