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