3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class CRM_Contact_Form_Merge.
21 class CRM_Contact_Form_Merge
extends CRM_Core_Form
{
22 // The id of the contact that there's a duplicate for; this one will
24 * possibly inherit some of $_oid's properties and remain in the system.
30 * The id of the other contact - the duplicate one that will get deleted.
35 public $_contactType = NULL;
40 public $criteria = [];
43 * Query limit to be retained in the urls.
50 * String for quickform bug handling.
52 * FIXME: QuickForm can't create advcheckboxes with value set to 0 or '0' :(
53 * see HTML_QuickForm_advcheckbox::setValues() - but patching that doesn't
54 * help, as QF doesn't put the 0-value elements in exportValues() anyway...
55 * to side-step this, we use the below UUID as a (re)placeholder
59 public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
61 public function preProcess() {
64 $this->_cid
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
65 $this->_oid
= CRM_Utils_Request
::retrieve('oid', 'Positive', $this, TRUE);
66 $flip = CRM_Utils_Request
::retrieve('flip', 'Positive', $this, FALSE);
68 $this->_rgid
= CRM_Utils_Request
::retrieve('rgid', 'Positive', $this, FALSE);
69 $this->_gid
= $gid = CRM_Utils_Request
::retrieve('gid', 'Positive', $this, FALSE);
70 $this->_mergeId
= CRM_Utils_Request
::retrieve('mergeId', 'Positive', $this, FALSE);
71 $this->limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this, FALSE);
72 $this->criteria
= CRM_Utils_Request
::retrieve('criteria', 'Json', $this, FALSE, '{}');
74 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid
, 'gid' => $this->_gid
, 'limit' => $this->limit
, 'criteria' => $this->criteria
];
76 $this->bounceIfInvalid($this->_cid
, $this->_oid
);
78 $contacts = civicrm_api3('Contact', 'get', [
79 'id' => ['IN' => [$this->_cid
, $this->_oid
]],
80 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
83 $this->_contactType
= $contacts[$this->_cid
]['contact_type'];
85 $browseUrl = CRM_Utils_System
::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
88 // Unset browse URL as we have come from the search screen.
91 $this->_rgid
= civicrm_api3('RuleGroup', 'getvalue', [
92 'contact_type' => $this->_contactType
,
93 'used' => 'Supervised',
97 catch (Exception
$e) {
98 throw new CRM_Core_Exception(ts('There is no Supervised dedupe rule configured for contact type %1.', [1 => $this->_contactType
]));
101 $this->assign('browseUrl', $browseUrl);
103 CRM_Core_Session
::singleton()->pushUserContext($browseUrl);
106 $cacheKey = CRM_Dedupe_Merger
::getMergeCacheKeyString($this->_rgid
, $gid, json_decode($this->criteria
, TRUE), TRUE, $this->limit
);
108 $join = CRM_Dedupe_Merger
::getJoinOnDedupeTable();
109 $where = "de.id IS NULL";
111 $pos = CRM_Core_BAO_PrevNextCache
::getPositions($cacheKey, $this->_cid
, $this->_oid
, $this->_mergeId
, $join, $where, $flip);
113 // get user info of main contact.
114 $config = CRM_Core_Config
::singleton();
115 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
117 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($this->_cid
);
120 // @todo also calculate & assign url here & get it out of getRowsElementsAndInfo as it is form layer functionality.
121 $mainUser = $config->userSystem
->getUser($this->_cid
);
122 $this->assign('mainUfId', $mainUfId);
123 $this->assign('mainUfName', $mainUser ?
$mainUser['name'] : NULL);
125 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid
, 'oid' => $this->_cid
]);
127 $flipParams['flip'] = '1';
129 $flipUrl = CRM_Utils_System
::url('civicrm/contact/merge',
132 $this->assign('flip', $flipUrl);
134 $this->prev
= $this->next
= NULL;
139 if (!empty($pos[$position])) {
140 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
141 $rowParams = array_merge($urlParams, [
142 'action' => 'update',
143 'cid' => $pos[$position]['id1'],
144 'oid' => $pos[$position]['id2'],
145 'mergeId' => $pos[$position]['mergeId'],
147 $this->$position = CRM_Utils_System
::url('civicrm/contact/merge', $rowParams);
148 $this->assign($position, $this->$position);
153 // get user info of other contact.
154 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($this->_oid
);
158 // @todo also calculate & assign url here & get it out of getRowsElementsAndInfo as it is form layer functionality.
159 $otherUser = $config->userSystem
->getUser($this->_oid
);
160 $this->assign('otherUfId', $otherUfId);
161 $this->assign('otherUfName', $otherUser ?
$otherUser['name'] : NULL);
164 $cmsUser = $mainUfId && $otherUfId;
165 $this->assign('user', $cmsUser);
167 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($this->_cid
, $this->_oid
);
168 $main = $this->_mainDetails
= $rowsElementsAndInfo['main_details'];
169 $other = $this->_otherDetails
= $rowsElementsAndInfo['other_details'];
171 $this->assign('contact_type', $main['contact_type']);
172 $this->assign('main_name', $main['display_name']);
173 $this->assign('other_name', $other['display_name']);
174 $this->assign('main_cid', $main['contact_id']);
175 $this->assign('other_cid', $other['contact_id']);
176 $this->assign('rgid', $this->_rgid
);
177 $this->assignSummaryRowsToTemplate($contacts);
179 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
181 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
182 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger
::getLocationBlockInfo()));
183 $this->assign('mainContactTypeIcon', CRM_Contact_BAO_Contact_Utils
::getImage($contacts[$this->_cid
]['contact_sub_type'] ?
$contacts[$this->_cid
]['contact_sub_type'] : $contacts[$this->_cid
]['contact_type'],
187 $this->assign('otherContactTypeIcon', CRM_Contact_BAO_Contact_Utils
::getImage($contacts[$this->_oid
]['contact_sub_type'] ?
$contacts[$this->_oid
]['contact_sub_type'] : $contacts[$this->_oid
]['contact_type'],
192 if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
193 // We don't permit merging contacts of different types so this is just clutter - putting
194 // the icon next to the contact name is consistent with elsewhere and permits hover-info
195 // https://lab.civicrm.org/dev/core/issues/824
196 unset($rowsElementsAndInfo['rows']['move_contact_type']);
199 $this->assign('rows', $rowsElementsAndInfo['rows']);
202 foreach ($rowsElementsAndInfo['elements'] as $element) {
203 // We could push this down to the getRowsElementsAndInfo function but it's
204 // already so overloaded - let's start moving towards doing form-things
206 if (substr($element[1], 0, 13) === 'move_location') {
207 $element[4] = array_merge(
208 (array) CRM_Utils_Array
::value(4, $element, []),
210 'data-location' => substr($element[1], 14),
211 'data-is_location' => TRUE,
214 if (substr($element[1], 0, 15) === 'location_blocks') {
215 // @todo We could add some data elements here to make jquery manipulation more straight-forward
216 // @todo consider enabling if it is an add & defaulting to true.
217 $element[4] = array_merge((array) CRM_Utils_Array
::value(4, $element, []), ['disabled' => TRUE]);
219 $newCheckBox = $this->addElement($element[0],
221 array_key_exists('2', $element) ?
$element[2] : NULL,
222 array_key_exists('3', $element) ?
$element[3] : NULL,
223 array_key_exists('4', $element) ?
$element[4] : NULL,
224 array_key_exists('5', $element) ?
$element[5] : NULL
226 if (!empty($element['is_checked'])) {
227 $newCheckBox->setChecked(TRUE);
231 // add related table elements
232 foreach (array_keys($rowsElementsAndInfo['rel_tables']) as $relTableElement) {
233 $this->addElement('checkbox', $relTableElement);
234 $this->_defaults
[$relTableElement] = 1;
237 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
238 $this->assign('userContextURL', CRM_Core_Session
::singleton()
239 ->readUserContext());
241 catch (CRM_Core_Exception
$e) {
242 CRM_Core_Error
::statusBounce($e->getMessage());
246 public function addRules() {
249 public function buildQuickForm() {
250 $this->unsavedChangesWarn
= FALSE;
251 CRM_Utils_System
::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType
]));
256 'name' => $this->next ?
ts('Merge and go to Next Pair') : ts('Merge'),
258 'icon' => $this->next ?
'fa-play-circle' : 'check',
261 if ($this->next ||
$this->prev
) {
264 'name' => ts('Merge and go to Listing'),
268 'name' => ts('Merge and View Result'),
269 'icon' => 'fa-check-circle',
275 'name' => ts('Cancel'),
278 $this->addButtons($buttons);
279 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
289 public static function formRule($fields, $files, $self) {
291 $link = CRM_Utils_System
::href(ts('Flip between the original and duplicate contacts.'),
292 'civicrm/contact/merge',
293 'reset=1&action=update&cid=' . $self->_oid
. '&oid=' . $self->_cid
. '&rgid=' . $self->_rgid
. '&flip=1'
295 if (CRM_Contact_BAO_Contact
::checkDomainContact($self->_oid
)) {
296 $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", [1 => $link]);
301 public function postProcess() {
302 $formValues = $this->exportValues();
304 $formValues['main_details'] = $this->_mainDetails
;
305 $formValues['other_details'] = $this->_otherDetails
;
306 $migrationData = ['migration_info' => $formValues];
307 CRM_Utils_Hook
::merge('form', $migrationData, $this->_cid
, $this->_oid
);
308 CRM_Dedupe_Merger
::moveAllBelongings($this->_cid
, $this->_oid
, $migrationData['migration_info']);
310 $name = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid
, 'display_name');
311 $message = '<ul><li>' . ts('%1 has been updated.', [1 => $name]) . '</li><li>' . ts('Contact ID %1 has been deleted.', [1 => $this->_oid
]) . '</li></ul>';
312 CRM_Core_Session
::setStatus($message, ts('Contacts Merged'), 'success');
314 $urlParams = ['reset' => 1, 'cid' => $this->_cid
, 'rgid' => $this->_rgid
, 'gid' => $this->_gid
, 'limit' => $this->limit
, 'criteria' => $this->criteria
];
315 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid
]);
317 if (!empty($formValues['_qf_Merge_submit'])) {
318 $urlParams['action'] = "update";
319 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/dedupefind',
323 if (!empty($formValues['_qf_Merge_done'])) {
324 CRM_Utils_System
::redirect($contactViewUrl);
327 if ($this->next
&& $this->_mergeId
) {
328 $cacheKey = CRM_Dedupe_Merger
::getMergeCacheKeyString($this->_rgid
, $this->_gid
, json_decode($this->criteria
, TRUE), TRUE, $this->limit
);
330 $join = CRM_Dedupe_Merger
::getJoinOnDedupeTable();
331 $where = "de.id IS NULL";
333 $pos = CRM_Core_BAO_PrevNextCache
::getPositions($cacheKey, NULL, NULL, $this->_mergeId
, $join, $where);
336 $pos['next']['id1'] &&
340 $urlParams['cid'] = $pos['next']['id1'];
341 $urlParams['oid'] = $pos['next']['id2'];
342 $urlParams['mergeId'] = $pos['next']['mergeId'];
343 $urlParams['action'] = 'update';
344 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/merge', $urlParams));
348 // Perhaps never reached.
349 CRM_Utils_System
::redirect($contactViewUrl);
353 * Bounce if the merge action is invalid.
355 * We don't allow the merge if it is nonsensical, marked as a duplicate
356 * or outside the user's permission.
359 * Contact ID to retain
361 * Contact ID to delete.
363 public function bounceIfInvalid($cid, $oid) {
365 CRM_Core_Error
::statusBounce(ts('Cannot merge a contact with itself.'));
368 if (!CRM_Dedupe_BAO_DedupeRule
::validateContacts($cid, $oid)) {
369 CRM_Core_Error
::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href="%1">Dedupe Exceptions</a> page.', [1 => CRM_Utils_System
::url('civicrm/dedupe/exception', 'reset=1')]));
372 if (!(CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
) &&
373 CRM_Contact_BAO_Contact_Permission
::allow($oid, CRM_Core_Permission
::EDIT
)
376 CRM_Utils_System
::permissionDenied();
378 // ensure that oid is not the current user, if so refuse to do the merge
379 if (CRM_Core_Session
::getLoggedInContactID() == $oid) {
380 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
381 [1 => CRM_Core_Session
::singleton()->getLoggedInContactDisplayName()]
383 CRM_Core_Error
::statusBounce($message);
388 * Assign the summary_rows variable to the tpl.
390 * This adds rows to the beginning of the block that will help in making merge choices.
392 * It can be modified by a hook by altering what is assigned. Although not technically supported this
393 * is an easy tweak with no earth-shattering impacts if later changes stop if from working.
395 * https://lab.civicrm.org/dev/core/issues/824
397 * @param array $contacts
399 protected function assignSummaryRowsToTemplate($contacts) {
400 $mostRecent = ($contacts[$this->_cid
]['modified_date'] < $contacts[$this->_oid
]['modified_date']) ?
$this->_oid
: $this->_cid
;
401 $this->assign('summary_rows', [
403 'name' => 'created_date',
404 'label' => ts('Created'),
405 'main_contact_value' => CRM_Utils_Date
::customFormat($contacts[$this->_cid
]['created_date']),
406 'other_contact_value' => CRM_Utils_Date
::customFormat($contacts[$this->_oid
]['created_date']),
409 'name' => 'modified_date',
410 'label' => ts('Last Modified'),
411 'main_contact_value' => CRM_Utils_Date
::customFormat($contacts[$this->_cid
]['modified_date']) . ($mostRecent == $this->_cid ?
' (' . ts('Most Recent') . ')' : ''),
412 'other_contact_value' => CRM_Utils_Date
::customFormat($contacts[$this->_oid
]['modified_date']) . ($mostRecent == $this->_oid ?
' (' . ts('Most Recent') . ')' : ''),
418 * Set the defaults for the form.
421 * Array of default values
423 public function setDefaultValues() {
424 return $this->_defaults
;