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