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