Import Summary - Update to match final schema ('UserJob.job_type')
[civicrm-core.git] / CRM / Contact / Form / Merge.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
86538308 18/**
5a409b50 19 * Class CRM_Contact_Form_Merge.
86538308 20 */
6a488035 21class CRM_Contact_Form_Merge extends CRM_Core_Form {
5af77f03 22 // The id of the contact that there's a duplicate for; this one will
69078420
SL
23 /**
24 * possibly inherit some of $_oid's properties and remain in the system.
25 * @var int
26 */
27 public $_cid = NULL;
6a488035 28
69078420
SL
29 /**
30 * The id of the other contact - the duplicate one that will get deleted.
31 * @var int
32 */
33 public $_oid = NULL;
6a488035 34
69078420 35 public $_contactType = NULL;
6a488035 36
9f54f049 37 /**
38 * @var array
39 */
be2fb01f 40 public $criteria = [];
9f54f049 41
dc6285d5 42 /**
43 * Query limit to be retained in the urls.
44 *
45 * @var int
46 */
69078420 47 public $limit;
dc6285d5 48
5af77f03 49 /**
50 * String for quickform bug handling.
51 *
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
56 *
57 * @var string
58 */
69078420 59 public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
8ef12e64 60
00be9182 61 public function preProcess() {
fcc3d8ee 62 try {
6a488035 63
fcc3d8ee 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);
6a488035 67
fcc3d8ee 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);
9f54f049 72 $this->criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE, '{}');
c0cc2ad4 73
9f54f049 74 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
6d5a3f21 75
fcc3d8ee 76 $this->bounceIfInvalid($this->_cid, $this->_oid);
186e5c44 77
c8e6c437 78 $contacts = civicrm_api3('Contact', 'get', [
79 'id' => ['IN' => [$this->_cid, $this->_oid]],
58edb71b 80 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
c8e6c437 81 ])['values'];
82
83 $this->_contactType = $contacts[$this->_cid]['contact_type'];
6a488035 84
c0cc2ad4 85 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
2ae26001 86
fcc3d8ee 87 if (!$this->_rgid) {
88 // Unset browse URL as we have come from the search screen.
89 $browseUrl = '';
eef25687
JP
90 try {
91 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', [
92 'contact_type' => $this->_contactType,
93 'used' => 'Supervised',
94 'return' => 'id',
95 ]);
96 }
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]));
99 }
fcc3d8ee 100 }
101 $this->assign('browseUrl', $browseUrl);
102 if ($browseUrl) {
103 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
104 }
6a488035 105
997a03fe 106 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
6a488035 107
fcc3d8ee 108 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
109 $where = "de.id IS NULL";
6a488035 110
fcc3d8ee 111 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
6a488035 112
fcc3d8ee 113 // get user info of main contact.
114 $config = CRM_Core_Config::singleton();
0626851e 115 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
6a488035 116
fcc3d8ee 117 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
118 $mainUser = NULL;
119 if ($mainUfId) {
8372e605 120 // @todo also calculate & assign url here & get it out of getRowsElementsAndInfo as it is form layer functionality.
cff0c9aa 121 $mainUser = $config->userSystem->getUser($this->_cid);
fcc3d8ee 122 $this->assign('mainUfId', $mainUfId);
cff0c9aa 123 $this->assign('mainUfName', $mainUser ? $mainUser['name'] : NULL);
fcc3d8ee 124 }
c0cc2ad4 125 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
fcc3d8ee 126 if (!$flip) {
c0cc2ad4 127 $flipParams['flip'] = '1';
6a488035 128 }
c0cc2ad4 129 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
130 $flipParams
131 );
fcc3d8ee 132 $this->assign('flip', $flipUrl);
133
134 $this->prev = $this->next = NULL;
a6f2a80f 135 foreach (['prev', 'next'] as $position) {
fcc3d8ee 136 if (!empty($pos[$position])) {
137 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
c0cc2ad4 138 $rowParams = array_merge($urlParams, [
139 'action' => 'update',
140 'cid' => $pos[$position]['id1'],
141 'oid' => $pos[$position]['id2'],
142 'mergeId' => $pos[$position]['mergeId'],
143 ]);
144 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
fcc3d8ee 145 }
146 }
a6f2a80f 147 $this->assign($position, $this->$position);
6a488035
TO
148 }
149
fcc3d8ee 150 // get user info of other contact.
151 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
152 $otherUser = NULL;
6a488035 153
fcc3d8ee 154 if ($otherUfId) {
8372e605 155 // @todo also calculate & assign url here & get it out of getRowsElementsAndInfo as it is form layer functionality.
cff0c9aa 156 $otherUser = $config->userSystem->getUser($this->_oid);
fcc3d8ee 157 }
a6f2a80f
CW
158 $this->assign('otherUfId', $otherUfId);
159 $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
6a488035 160
dc0aa487 161 $cmsUser = $mainUfId && $otherUfId;
fcc3d8ee 162 $this->assign('user', $cmsUser);
163
164 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
165 $main = $this->_mainDetails = $rowsElementsAndInfo['main_details'];
166 $other = $this->_otherDetails = $rowsElementsAndInfo['other_details'];
167
168 $this->assign('contact_type', $main['contact_type']);
169 $this->assign('main_name', $main['display_name']);
170 $this->assign('other_name', $other['display_name']);
171 $this->assign('main_cid', $main['contact_id']);
172 $this->assign('other_cid', $other['contact_id']);
173 $this->assign('rgid', $this->_rgid);
c8e6c437 174 $this->assignSummaryRowsToTemplate($contacts);
fcc3d8ee 175
be2fb01f 176 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
fcc3d8ee 177
178 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
179 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
58edb71b 180 $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'],
181 FALSE,
182 $this->_cid
183 ));
184 $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'],
185 FALSE,
186 $this->_oid
187 ));
188
189 if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
190 // We don't permit merging contacts of different types so this is just clutter - putting
191 // the icon next to the contact name is consistent with elsewhere and permits hover-info
192 // https://lab.civicrm.org/dev/core/issues/824
193 unset($rowsElementsAndInfo['rows']['move_contact_type']);
194 }
195
f9a69126
EM
196 $assignedRows = $rowsElementsAndInfo['rows'];
197 foreach ($assignedRows as $index => $assignedRow) {
198 // prevent smarty notices.
a6f2a80f
CW
199 $assignedRows[$index] += [
200 'main' => NULL,
201 'other' => NULL,
202 'location_entity' => NULL,
203 ];
f9a69126
EM
204 }
205 $this->assign('rows', $assignedRows);
fcc3d8ee 206
207 // add elements
208 foreach ($rowsElementsAndInfo['elements'] as $element) {
209 // We could push this down to the getRowsElementsAndInfo function but it's
210 // already so overloaded - let's start moving towards doing form-things
211 // on the form.
212 if (substr($element[1], 0, 13) === 'move_location') {
213 $element[4] = array_merge(
be2fb01f
CW
214 (array) CRM_Utils_Array::value(4, $element, []),
215 [
fcc3d8ee 216 'data-location' => substr($element[1], 14),
217 'data-is_location' => TRUE,
be2fb01f 218 ]);
fcc3d8ee 219 }
220 if (substr($element[1], 0, 15) === 'location_blocks') {
221 // @todo We could add some data elements here to make jquery manipulation more straight-forward
222 // @todo consider enabling if it is an add & defaulting to true.
be2fb01f 223 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
fcc3d8ee 224 }
3d1d395a 225 $newCheckBox = $this->addElement($element[0],
fcc3d8ee 226 $element[1],
227 array_key_exists('2', $element) ? $element[2] : NULL,
228 array_key_exists('3', $element) ? $element[3] : NULL,
229 array_key_exists('4', $element) ? $element[4] : NULL,
230 array_key_exists('5', $element) ? $element[5] : NULL
231 );
3d1d395a 232 if (!empty($element['is_checked'])) {
233 $newCheckBox->setChecked(TRUE);
234 }
972e23db 235 }
fcc3d8ee 236
237 // add related table elements
c813e8f4 238 foreach (array_keys($rowsElementsAndInfo['rel_tables']) as $relTableElement) {
a314f452
SL
239 $this->addElement('checkbox', $relTableElement);
240 $this->_defaults[$relTableElement] = 1;
972e23db 241 }
6a488035 242
fcc3d8ee 243 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
244 $this->assign('userContextURL', CRM_Core_Session::singleton()
245 ->readUserContext());
246 }
247 catch (CRM_Core_Exception $e) {
1836ab9e 248 CRM_Core_Error::statusBounce($e->getMessage());
6a488035 249 }
6a488035
TO
250 }
251
6ea503d4
TO
252 public function addRules() {
253 }
6a488035
TO
254
255 public function buildQuickForm() {
d45c349e 256 $this->unsavedChangesWarn = FALSE;
7e2e2551 257 $this->setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
be2fb01f 258 $buttons = [];
fd66df85 259
be2fb01f 260 $buttons[] = [
fd66df85 261 'type' => 'next',
3709190a 262 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
fd66df85 263 'isDefault' => TRUE,
a6f2a80f 264 'icon' => $this->next ? 'fa-play-circle' : 'fa-check',
be2fb01f 265 ];
6a488035
TO
266
267 if ($this->next || $this->prev) {
be2fb01f 268 $buttons[] = [
fd66df85 269 'type' => 'submit',
3709190a 270 'name' => ts('Merge and go to Listing'),
be2fb01f
CW
271 ];
272 $buttons[] = [
fd66df85
CW
273 'type' => 'done',
274 'name' => ts('Merge and View Result'),
0291a521 275 'icon' => 'fa-check-circle',
be2fb01f 276 ];
6a488035
TO
277 }
278
be2fb01f 279 $buttons[] = [
fd66df85
CW
280 'type' => 'cancel',
281 'name' => ts('Cancel'),
be2fb01f 282 ];
fd66df85
CW
283
284 $this->addButtons($buttons);
be2fb01f 285 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
4b87bd02 286 }
287
86538308
EM
288 /**
289 * @param $fields
290 * @param $files
e8cf95b4 291 * @param self $self
86538308
EM
292 *
293 * @return array
294 */
00be9182 295 public static function formRule($fields, $files, $self) {
be2fb01f 296 $errors = [];
0653585f 297 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
b74201e4 298 'civicrm/contact/merge',
299 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
300 );
4b87bd02 301 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
be2fb01f 302 $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]);
4b87bd02 303 }
304 return $errors;
6a488035
TO
305 }
306
307 public function postProcess() {
308 $formValues = $this->exportValues();
8ef12e64 309
471ec338
BS
310 $formValues['main_details'] = $this->_mainDetails;
311 $formValues['other_details'] = $this->_otherDetails;
22f453ce
JF
312
313 // Check if any rel_tables checkboxes have been de-selected
314 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
315 // If rel_tables is not set then initialise with 0 value, required for the check which calls removeContactBelongings in moveAllBelongings
316 foreach (array_keys($rowsElementsAndInfo['rel_tables']) as $relTableElement) {
317 if (!array_key_exists($relTableElement, $formValues)) {
318 $formValues[$relTableElement] = '0';
319 }
320 }
be2fb01f 321 $migrationData = ['migration_info' => $formValues];
22f453ce 322
b54f692d 323 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
324 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
6a488035 325
7b99ead3 326 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
be2fb01f 327 $message = '<ul><li>' . ts('%1 has been updated.', [1 => $name]) . '</li><li>' . ts('Contact ID %1 has been deleted.', [1 => $this->_oid]) . '</li></ul>';
7b99ead3
CW
328 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
329
9f54f049 330 $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
dc6285d5 331
afa4f120 332 // When clicking "Merge and go to listing"
a7488080 333 if (!empty($formValues['_qf_Merge_submit'])) {
c0cc2ad4 334 $urlParams['action'] = "update";
afa4f120 335 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParams));
6a488035 336 }
afa4f120 337 // When clicking "Merge and go to next pair"
37e81bb4 338 elseif ($this->next && $this->_mergeId && empty($formValues['_qf_Merge_done'])) {
997a03fe 339 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
6a488035 340
2ae26001 341 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
6a488035
TO
342 $where = "de.id IS NULL";
343
344 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
345
346 if (!empty($pos) &&
347 $pos['next']['id1'] &&
348 $pos['next']['id2']
349 ) {
350
c0cc2ad4 351 $urlParams['cid'] = $pos['next']['id1'];
352 $urlParams['oid'] = $pos['next']['id2'];
353 $urlParams['mergeId'] = $pos['next']['mergeId'];
354 $urlParams['action'] = 'update';
afa4f120 355 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/merge', $urlParams));
6a488035
TO
356 }
357 }
afa4f120
CW
358 // When clicking "Merge and View Result" or when used from search forms
359 // Note: search might load this action in a popup, so cannot use a redirect.
360 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid]);
361 CRM_Core_Session::singleton()->pushUserContext($contactViewUrl);
362 // I think this bit is needed because this is a multi-step form.
363 $this->controller->setDestination($contactViewUrl);
6a488035 364 }
96025800 365
fa74cac4 366 /**
367 * Bounce if the merge action is invalid.
368 *
369 * We don't allow the merge if it is nonsensical, marked as a duplicate
370 * or outside the user's permission.
371 *
372 * @param int $cid
373 * Contact ID to retain
374 * @param int $oid
375 * Contact ID to delete.
376 */
377 public function bounceIfInvalid($cid, $oid) {
378 if ($cid == $oid) {
379 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
380 }
381
61194d45 382 if (!CRM_Dedupe_BAO_DedupeRule::validateContacts($cid, $oid)) {
be2fb01f 383 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')]));
fa74cac4 384 }
385
386 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
387 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
388 )
389 ) {
390 CRM_Utils_System::permissionDenied();
391 }
392 // ensure that oid is not the current user, if so refuse to do the merge
2dbdb9b9 393 if (CRM_Core_Session::getLoggedInContactID() == $oid) {
fa74cac4 394 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
be2fb01f 395 [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
fa74cac4 396 );
397 CRM_Core_Error::statusBounce($message);
398 }
399 }
400
c8e6c437 401 /**
402 * Assign the summary_rows variable to the tpl.
403 *
404 * This adds rows to the beginning of the block that will help in making merge choices.
405 *
406 * It can be modified by a hook by altering what is assigned. Although not technically supported this
407 * is an easy tweak with no earth-shattering impacts if later changes stop if from working.
408 *
409 * https://lab.civicrm.org/dev/core/issues/824
410 *
411 * @param array $contacts
412 */
413 protected function assignSummaryRowsToTemplate($contacts) {
414 $mostRecent = ($contacts[$this->_cid]['modified_date'] < $contacts[$this->_oid]['modified_date']) ? $this->_oid : $this->_cid;
415 $this->assign('summary_rows', [
416 [
417 'name' => 'created_date',
418 'label' => ts('Created'),
419 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['created_date']),
420 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['created_date']),
421 ],
422 [
423 'name' => 'modified_date',
424 'label' => ts('Last Modified'),
425 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['modified_date']) . ($mostRecent == $this->_cid ? ' (' . ts('Most Recent') . ')' : ''),
426 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['modified_date']) . ($mostRecent == $this->_oid ? ' (' . ts('Most Recent') . ')' : ''),
427 ],
428 ]);
429 }
430
ae57ddac 431 /**
432 * Set the defaults for the form.
433 *
434 * @return array
435 * Array of default values
436 */
437 public function setDefaultValues() {
438 return $this->_defaults;
439 }
440
6a488035 441}