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