Merge pull request #18907 from alifrumin/2139
[civicrm-core.git] / CRM / Contact / Form / Merge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class CRM_Contact_Form_Merge.
20 */
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
23 /**
24 * possibly inherit some of $_oid's properties and remain in the system.
25 * @var int
26 */
27 public $_cid = NULL;
28
29 /**
30 * The id of the other contact - the duplicate one that will get deleted.
31 * @var int
32 */
33 public $_oid = NULL;
34
35 public $_contactType = NULL;
36
37 /**
38 * @var array
39 */
40 public $criteria = [];
41
42 /**
43 * Query limit to be retained in the urls.
44 *
45 * @var int
46 */
47 public $limit;
48
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 */
59 public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
60
61 public function preProcess() {
62 try {
63
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);
67
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, '{}');
73
74 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
75
76 $this->bounceIfInvalid($this->_cid, $this->_oid);
77
78 $contacts = civicrm_api3('Contact', 'get', [
79 'id' => ['IN' => [$this->_cid, $this->_oid]],
80 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
81 ])['values'];
82
83 $this->_contactType = $contacts[$this->_cid]['contact_type'];
84
85 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
86
87 if (!$this->_rgid) {
88 // Unset browse URL as we have come from the search screen.
89 $browseUrl = '';
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 }
100 }
101 $this->assign('browseUrl', $browseUrl);
102 if ($browseUrl) {
103 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
104 }
105
106 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
107
108 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
109 $where = "de.id IS NULL";
110
111 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
112
113 // get user info of main contact.
114 $config = CRM_Core_Config::singleton();
115 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
116
117 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
118 $mainUser = NULL;
119 if ($mainUfId) {
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);
124 }
125 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
126 if (!$flip) {
127 $flipParams['flip'] = '1';
128 }
129 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
130 $flipParams
131 );
132 $this->assign('flip', $flipUrl);
133
134 $this->prev = $this->next = NULL;
135 foreach ([
136 'prev',
137 'next',
138 ] as $position) {
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'],
146 ]);
147 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
148 $this->assign($position, $this->$position);
149 }
150 }
151 }
152
153 // get user info of other contact.
154 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
155 $otherUser = NULL;
156
157 if ($otherUfId) {
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);
162 }
163
164 $cmsUser = $mainUfId && $otherUfId;
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);
177 $this->assignSummaryRowsToTemplate($contacts);
178
179 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
180
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'],
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
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(
208 (array) CRM_Utils_Array::value(4, $element, []),
209 [
210 'data-location' => substr($element[1], 14),
211 'data-is_location' => TRUE,
212 ]);
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.
217 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
218 }
219 $newCheckBox = $this->addElement($element[0],
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 );
226 if (!empty($element['is_checked'])) {
227 $newCheckBox->setChecked(TRUE);
228 }
229 }
230
231 // add related table elements
232 foreach (array_keys($rowsElementsAndInfo['rel_tables']) as $relTableElement) {
233 $this->addElement('checkbox', $relTableElement);
234 $this->_defaults[$relTableElement] = 1;
235 }
236
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) {
242 CRM_Core_Error::statusBounce($e->getMessage());
243 }
244 }
245
246 public function addRules() {
247 }
248
249 public function buildQuickForm() {
250 $this->unsavedChangesWarn = FALSE;
251 CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
252 $buttons = [];
253
254 $buttons[] = [
255 'type' => 'next',
256 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
257 'isDefault' => TRUE,
258 'icon' => $this->next ? 'fa-play-circle' : 'check',
259 ];
260
261 if ($this->next || $this->prev) {
262 $buttons[] = [
263 'type' => 'submit',
264 'name' => ts('Merge and go to Listing'),
265 ];
266 $buttons[] = [
267 'type' => 'done',
268 'name' => ts('Merge and View Result'),
269 'icon' => 'fa-check-circle',
270 ];
271 }
272
273 $buttons[] = [
274 'type' => 'cancel',
275 'name' => ts('Cancel'),
276 ];
277
278 $this->addButtons($buttons);
279 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
280 }
281
282 /**
283 * @param $fields
284 * @param $files
285 * @param $self
286 *
287 * @return array
288 */
289 public static function formRule($fields, $files, $self) {
290 $errors = [];
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'
294 );
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]);
297 }
298 return $errors;
299 }
300
301 public function postProcess() {
302 $formValues = $this->exportValues();
303
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']);
309
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');
313
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]);
316
317 if (!empty($formValues['_qf_Merge_submit'])) {
318 $urlParams['action'] = "update";
319 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind',
320 $urlParams
321 ));
322 }
323 if (!empty($formValues['_qf_Merge_done'])) {
324 CRM_Utils_System::redirect($contactViewUrl);
325 }
326
327 if ($this->next && $this->_mergeId) {
328 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
329
330 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
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
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));
345 }
346 }
347
348 // Perhaps never reached.
349 CRM_Utils_System::redirect($contactViewUrl);
350 }
351
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)) {
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')]));
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::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()]
382 );
383 CRM_Core_Error::statusBounce($message);
384 }
385 }
386
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
417 /**
418 * Set the defaults for the form.
419 *
420 * @return array
421 * Array of default values
422 */
423 public function setDefaultValues() {
424 return $this->_defaults;
425 }
426
427 }