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