Convert remaining Authorize.net test to use guzzle
[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;
be2fb01f 135 foreach ([
69078420
SL
136 'prev',
137 'next',
138 ] as $position) {
fcc3d8ee 139 if (!empty($pos[$position])) {
140 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
c0cc2ad4 141 $rowParams = array_merge($urlParams, [
142 'action' => 'update',
143 'cid' => $pos[$position]['id1'],
144 'oid' => $pos[$position]['id2'],
145 'mergeId' => $pos[$position]['mergeId'],
146 ]);
147 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
fcc3d8ee 148 $this->assign($position, $this->$position);
149 }
150 }
6a488035
TO
151 }
152
fcc3d8ee 153 // get user info of other contact.
154 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
155 $otherUser = NULL;
6a488035 156
fcc3d8ee 157 if ($otherUfId) {
8372e605 158 // @todo also calculate & assign url here & get it out of getRowsElementsAndInfo as it is form layer functionality.
cff0c9aa 159 $otherUser = $config->userSystem->getUser($this->_oid);
fcc3d8ee 160 $this->assign('otherUfId', $otherUfId);
cff0c9aa 161 $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
fcc3d8ee 162 }
6a488035 163
dc0aa487 164 $cmsUser = $mainUfId && $otherUfId;
fcc3d8ee 165 $this->assign('user', $cmsUser);
166
167 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
168 $main = $this->_mainDetails = $rowsElementsAndInfo['main_details'];
169 $other = $this->_otherDetails = $rowsElementsAndInfo['other_details'];
170
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);
c8e6c437 177 $this->assignSummaryRowsToTemplate($contacts);
fcc3d8ee 178
be2fb01f 179 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
fcc3d8ee 180
181 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
182 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
58edb71b 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'],
184 FALSE,
185 $this->_cid
186 ));
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'],
188 FALSE,
189 $this->_oid
190 ));
191
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']);
197 }
198
fcc3d8ee 199 $this->assign('rows', $rowsElementsAndInfo['rows']);
200
201 // add elements
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
205 // on the form.
206 if (substr($element[1], 0, 13) === 'move_location') {
207 $element[4] = array_merge(
be2fb01f
CW
208 (array) CRM_Utils_Array::value(4, $element, []),
209 [
fcc3d8ee 210 'data-location' => substr($element[1], 14),
211 'data-is_location' => TRUE,
be2fb01f 212 ]);
fcc3d8ee 213 }
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.
be2fb01f 217 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
fcc3d8ee 218 }
3d1d395a 219 $newCheckBox = $this->addElement($element[0],
fcc3d8ee 220 $element[1],
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
225 );
3d1d395a 226 if (!empty($element['is_checked'])) {
227 $newCheckBox->setChecked(TRUE);
228 }
972e23db 229 }
fcc3d8ee 230
231 // add related table elements
232 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
233 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
234 $element->setChecked(TRUE);
972e23db 235 }
6a488035 236
fcc3d8ee 237 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
238 $this->assign('userContextURL', CRM_Core_Session::singleton()
239 ->readUserContext());
240 }
241 catch (CRM_Core_Exception $e) {
1836ab9e 242 CRM_Core_Error::statusBounce($e->getMessage());
6a488035 243 }
6a488035
TO
244 }
245
6ea503d4
TO
246 public function addRules() {
247 }
6a488035
TO
248
249 public function buildQuickForm() {
d45c349e 250 $this->unsavedChangesWarn = FALSE;
be2fb01f
CW
251 CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
252 $buttons = [];
fd66df85 253
be2fb01f 254 $buttons[] = [
fd66df85 255 'type' => 'next',
3709190a 256 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
fd66df85 257 'isDefault' => TRUE,
5db72c32 258 'icon' => $this->next ? 'fa-play-circle' : 'check',
be2fb01f 259 ];
6a488035
TO
260
261 if ($this->next || $this->prev) {
be2fb01f 262 $buttons[] = [
fd66df85 263 'type' => 'submit',
3709190a 264 'name' => ts('Merge and go to Listing'),
be2fb01f
CW
265 ];
266 $buttons[] = [
fd66df85
CW
267 'type' => 'done',
268 'name' => ts('Merge and View Result'),
0291a521 269 'icon' => 'fa-check-circle',
be2fb01f 270 ];
6a488035
TO
271 }
272
be2fb01f 273 $buttons[] = [
fd66df85
CW
274 'type' => 'cancel',
275 'name' => ts('Cancel'),
be2fb01f 276 ];
fd66df85
CW
277
278 $this->addButtons($buttons);
be2fb01f 279 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
4b87bd02 280 }
281
86538308
EM
282 /**
283 * @param $fields
284 * @param $files
285 * @param $self
286 *
287 * @return array
288 */
00be9182 289 public static function formRule($fields, $files, $self) {
be2fb01f 290 $errors = [];
0653585f 291 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
b74201e4 292 'civicrm/contact/merge',
293 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
294 );
4b87bd02 295 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
be2fb01f 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]);
4b87bd02 297 }
298 return $errors;
6a488035
TO
299 }
300
301 public function postProcess() {
302 $formValues = $this->exportValues();
8ef12e64 303
471ec338
BS
304 $formValues['main_details'] = $this->_mainDetails;
305 $formValues['other_details'] = $this->_otherDetails;
be2fb01f 306 $migrationData = ['migration_info' => $formValues];
b54f692d 307 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
308 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
6a488035 309
7b99ead3 310 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
be2fb01f 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>';
7b99ead3
CW
312 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
313
9f54f049 314 $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
c0cc2ad4 315 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid]);
dc6285d5 316
a7488080 317 if (!empty($formValues['_qf_Merge_submit'])) {
c0cc2ad4 318 $urlParams['action'] = "update";
319 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind',
dc6285d5 320 $urlParams
c0cc2ad4 321 ));
6a488035 322 }
353ffa53 323 if (!empty($formValues['_qf_Merge_done'])) {
c0cc2ad4 324 CRM_Utils_System::redirect($contactViewUrl);
6a488035
TO
325 }
326
327 if ($this->next && $this->_mergeId) {
997a03fe 328 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
6a488035 329
2ae26001 330 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
6a488035
TO
331 $where = "de.id IS NULL";
332
333 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
334
335 if (!empty($pos) &&
336 $pos['next']['id1'] &&
337 $pos['next']['id2']
338 ) {
339
c0cc2ad4 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));
6a488035
TO
345 }
346 }
347
c0cc2ad4 348 // Perhaps never reached.
349 CRM_Utils_System::redirect($contactViewUrl);
6a488035 350 }
96025800 351
fa74cac4 352 /**
353 * Bounce if the merge action is invalid.
354 *
355 * We don't allow the merge if it is nonsensical, marked as a duplicate
356 * or outside the user's permission.
357 *
358 * @param int $cid
359 * Contact ID to retain
360 * @param int $oid
361 * Contact ID to delete.
362 */
363 public function bounceIfInvalid($cid, $oid) {
364 if ($cid == $oid) {
365 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
366 }
367
368 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
be2fb01f 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')]));
fa74cac4 370 }
371
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)
374 )
375 ) {
376 CRM_Utils_System::permissionDenied();
377 }
378 // ensure that oid is not the current user, if so refuse to do the merge
379 if (CRM_Core_Session::singleton()->getLoggedInContactID() == $oid) {
380 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
be2fb01f 381 [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
fa74cac4 382 );
383 CRM_Core_Error::statusBounce($message);
384 }
385 }
386
c8e6c437 387 /**
388 * Assign the summary_rows variable to the tpl.
389 *
390 * This adds rows to the beginning of the block that will help in making merge choices.
391 *
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.
394 *
395 * https://lab.civicrm.org/dev/core/issues/824
396 *
397 * @param array $contacts
398 */
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', [
402 [
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']),
407 ],
408 [
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') . ')' : ''),
413 ],
414 ]);
415 }
416
6a488035 417}