(NFC) (dev/core#878) Simplify copyright header (templates/*)
[civicrm-core.git] / CRM / Contact / Form / Merge.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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 +--------------------------------------------------------------------+
26 */
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC https://civicrm.org/licensing
32 */
33
34/**
35 * Class CRM_Contact_Form_Merge.
36 */
37class CRM_Contact_Form_Merge extends CRM_Core_Form {
38 // The id of the contact that there's a duplicate for; this one will
39 /**
40 * possibly inherit some of $_oid's properties and remain in the system.
41 * @var int
42 */
43 public $_cid = NULL;
44
45 /**
46 * The id of the other contact - the duplicate one that will get deleted.
47 * @var int
48 */
49 public $_oid = NULL;
50
51 public $_contactType = NULL;
52
53 /**
54 * @var array
55 */
56 public $criteria = [];
57
58 /**
59 * Query limit to be retained in the urls.
60 *
61 * @var int
62 */
63 public $limit;
64
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 */
75 public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
76
77 public function preProcess() {
78 try {
79
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);
83
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);
88 $this->criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE, '{}');
89
90 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
91
92 $this->bounceIfInvalid($this->_cid, $this->_oid);
93
94 $contacts = civicrm_api3('Contact', 'get', [
95 'id' => ['IN' => [$this->_cid, $this->_oid]],
96 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
97 ])['values'];
98
99 $this->_contactType = $contacts[$this->_cid]['contact_type'];
100
101 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
102
103 if (!$this->_rgid) {
104 // Unset browse URL as we have come from the search screen.
105 $browseUrl = '';
106 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', [
107 'contact_type' => $this->_contactType,
108 'used' => 'Supervised',
109 'return' => 'id',
110 ]);
111 }
112 $this->assign('browseUrl', $browseUrl);
113 if ($browseUrl) {
114 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
115 }
116
117 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
118
119 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
120 $where = "de.id IS NULL";
121
122 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
123
124 // get user info of main contact.
125 $config = CRM_Core_Config::singleton();
126 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
127
128 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
129 $mainUser = NULL;
130 if ($mainUfId) {
131 $mainUser = $config->userSystem->getUser($this->_cid);
132 $this->assign('mainUfId', $mainUfId);
133 $this->assign('mainUfName', $mainUser ? $mainUser['name'] : NULL);
134 }
135 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
136 if (!$flip) {
137 $flipParams['flip'] = '1';
138 }
139 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
140 $flipParams
141 );
142 $this->assign('flip', $flipUrl);
143
144 $this->prev = $this->next = NULL;
145 foreach ([
146 'prev',
147 'next',
148 ] as $position) {
149 if (!empty($pos[$position])) {
150 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
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);
158 $this->assign($position, $this->$position);
159 }
160 }
161 }
162
163 // get user info of other contact.
164 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
165 $otherUser = NULL;
166
167 if ($otherUfId) {
168 $otherUser = $config->userSystem->getUser($this->_oid);
169 $this->assign('otherUfId', $otherUfId);
170 $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
171 }
172
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);
186 $this->assignSummaryRowsToTemplate($contacts);
187
188 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
189
190 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
191 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
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
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(
217 (array) CRM_Utils_Array::value(4, $element, []),
218 [
219 'data-location' => substr($element[1], 14),
220 'data-is_location' => TRUE,
221 ]);
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.
226 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
227 }
228 $newCheckBox = $this->addElement($element[0],
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 );
235 if (!empty($element['is_checked'])) {
236 $newCheckBox->setChecked(TRUE);
237 }
238 }
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);
244 }
245
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) {
251 CRM_Core_Error::statusBounce($e->getMessage());
252 }
253 }
254
255 public function addRules() {
256 }
257
258 public function buildQuickForm() {
259 $this->unsavedChangesWarn = FALSE;
260 CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
261 $buttons = [];
262
263 $buttons[] = [
264 'type' => 'next',
265 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
266 'isDefault' => TRUE,
267 'icon' => $this->next ? 'fa-play-circle' : 'check',
268 ];
269
270 if ($this->next || $this->prev) {
271 $buttons[] = [
272 'type' => 'submit',
273 'name' => ts('Merge and go to Listing'),
274 ];
275 $buttons[] = [
276 'type' => 'done',
277 'name' => ts('Merge and View Result'),
278 'icon' => 'fa-check-circle',
279 ];
280 }
281
282 $buttons[] = [
283 'type' => 'cancel',
284 'name' => ts('Cancel'),
285 ];
286
287 $this->addButtons($buttons);
288 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
289 }
290
291 /**
292 * @param $fields
293 * @param $files
294 * @param $self
295 *
296 * @return array
297 */
298 public static function formRule($fields, $files, $self) {
299 $errors = [];
300 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
301 'civicrm/contact/merge',
302 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
303 );
304 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
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]);
306 }
307 return $errors;
308 }
309
310 public function postProcess() {
311 $formValues = $this->exportValues();
312
313 $formValues['main_details'] = $this->_mainDetails;
314 $formValues['other_details'] = $this->_otherDetails;
315 $migrationData = ['migration_info' => $formValues];
316 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
317 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
318
319 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
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>';
321 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
322
323 $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
324 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid]);
325
326 if (!empty($formValues['_qf_Merge_submit'])) {
327 $urlParams['action'] = "update";
328 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind',
329 $urlParams
330 ));
331 }
332 if (!empty($formValues['_qf_Merge_done'])) {
333 CRM_Utils_System::redirect($contactViewUrl);
334 }
335
336 if ($this->next && $this->_mergeId) {
337 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
338
339 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
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
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));
354 }
355 }
356
357 // Perhaps never reached.
358 CRM_Utils_System::redirect($contactViewUrl);
359 }
360
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)) {
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')]));
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.',
390 [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
391 );
392 CRM_Core_Error::statusBounce($message);
393 }
394 }
395
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
426}