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