Merge pull request #13158 from elisseck/dev/core/544
[civicrm-core.git] / CRM / Contact / Form / Merge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 (c) 2004-2019
32 */
33
34 /**
35 * Class CRM_Contact_Form_Merge.
36 */
37 class CRM_Contact_Form_Merge extends CRM_Core_Form {
38 // The id of the contact that there's a duplicate for; this one will
39 // possibly inherit some of $_oid's properties and remain in the system.
40 var $_cid = NULL;
41
42 // The id of the other contact - the duplicate one that will get deleted.
43 var $_oid = NULL;
44
45 var $_contactType = NULL;
46
47 /**
48 * @var array
49 */
50 public $criteria = array();
51
52 /**
53 * Query limit to be retained in the urls.
54 *
55 * @var int
56 */
57 var $limit;
58
59 /**
60 * String for quickform bug handling.
61 *
62 * FIXME: QuickForm can't create advcheckboxes with value set to 0 or '0' :(
63 * see HTML_QuickForm_advcheckbox::setValues() - but patching that doesn't
64 * help, as QF doesn't put the 0-value elements in exportValues() anyway...
65 * to side-step this, we use the below UUID as a (re)placeholder
66 *
67 * @var string
68 */
69 var $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
70
71 public function preProcess() {
72 try {
73
74 $this->_cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
75 $this->_oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
76 $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
77
78 $this->_rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
79 $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
80 $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
81 $this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
82 $this->criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE, '{}');
83
84 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
85
86 $this->bounceIfInvalid($this->_cid, $this->_oid);
87
88 $contacts = civicrm_api3('Contact', 'get', [
89 'id' => ['IN' => [$this->_cid, $this->_oid]],
90 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
91 ])['values'];
92
93 $this->_contactType = $contacts[$this->_cid]['contact_type'];
94
95 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
96
97 if (!$this->_rgid) {
98 // Unset browse URL as we have come from the search screen.
99 $browseUrl = '';
100 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array(
101 'contact_type' => $this->_contactType,
102 'used' => 'Supervised',
103 'return' => 'id',
104 ));
105 }
106 $this->assign('browseUrl', $browseUrl);
107 if ($browseUrl) {
108 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
109 }
110
111 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE));
112
113 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
114 $where = "de.id IS NULL";
115
116 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
117
118 // get user info of main contact.
119 $config = CRM_Core_Config::singleton();
120 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
121
122 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
123 $mainUser = NULL;
124 if ($mainUfId) {
125 $mainUser = $config->userSystem->getUser($this->_cid);
126 $this->assign('mainUfId', $mainUfId);
127 $this->assign('mainUfName', $mainUser ? $mainUser['name'] : NULL);
128 }
129 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
130 if (!$flip) {
131 $flipParams['flip'] = '1';
132 }
133 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
134 $flipParams
135 );
136 $this->assign('flip', $flipUrl);
137
138 $this->prev = $this->next = NULL;
139 foreach (array(
140 'prev',
141 'next',
142 ) as $position) {
143 if (!empty($pos[$position])) {
144 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
145 $rowParams = array_merge($urlParams, [
146 'action' => 'update',
147 'cid' => $pos[$position]['id1'],
148 'oid' => $pos[$position]['id2'],
149 'mergeId' => $pos[$position]['mergeId'],
150 ]);
151 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
152 $this->assign($position, $this->$position);
153 }
154 }
155 }
156
157 // get user info of other contact.
158 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
159 $otherUser = NULL;
160
161 if ($otherUfId) {
162 $otherUser = $config->userSystem->getUser($this->_oid);
163 $this->assign('otherUfId', $otherUfId);
164 $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
165 }
166
167 $cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
168 $this->assign('user', $cmsUser);
169
170 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
171 $main = $this->_mainDetails = $rowsElementsAndInfo['main_details'];
172 $other = $this->_otherDetails = $rowsElementsAndInfo['other_details'];
173
174 $this->assign('contact_type', $main['contact_type']);
175 $this->assign('main_name', $main['display_name']);
176 $this->assign('other_name', $other['display_name']);
177 $this->assign('main_cid', $main['contact_id']);
178 $this->assign('other_cid', $other['contact_id']);
179 $this->assign('rgid', $this->_rgid);
180 $this->assignSummaryRowsToTemplate($contacts);
181
182 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
183
184 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
185 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
186 $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'],
187 FALSE,
188 $this->_cid
189 ));
190 $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'],
191 FALSE,
192 $this->_oid
193 ));
194
195 if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
196 // We don't permit merging contacts of different types so this is just clutter - putting
197 // the icon next to the contact name is consistent with elsewhere and permits hover-info
198 // https://lab.civicrm.org/dev/core/issues/824
199 unset($rowsElementsAndInfo['rows']['move_contact_type']);
200 }
201
202 $this->assign('rows', $rowsElementsAndInfo['rows']);
203
204 // add elements
205 foreach ($rowsElementsAndInfo['elements'] as $element) {
206 // We could push this down to the getRowsElementsAndInfo function but it's
207 // already so overloaded - let's start moving towards doing form-things
208 // on the form.
209 if (substr($element[1], 0, 13) === 'move_location') {
210 $element[4] = array_merge(
211 (array) CRM_Utils_Array::value(4, $element, array()),
212 array(
213 'data-location' => substr($element[1], 14),
214 'data-is_location' => TRUE,
215 ));
216 }
217 if (substr($element[1], 0, 15) === 'location_blocks') {
218 // @todo We could add some data elements here to make jquery manipulation more straight-forward
219 // @todo consider enabling if it is an add & defaulting to true.
220 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, array()), array('disabled' => TRUE));
221 }
222 $this->addElement($element[0],
223 $element[1],
224 array_key_exists('2', $element) ? $element[2] : NULL,
225 array_key_exists('3', $element) ? $element[3] : NULL,
226 array_key_exists('4', $element) ? $element[4] : NULL,
227 array_key_exists('5', $element) ? $element[5] : NULL
228 );
229 }
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);
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(ts($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', array(1 => $this->_contactType)));
252 $buttons = array();
253
254 $buttons[] = array(
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[] = array(
263 'type' => 'submit',
264 'name' => ts('Merge and go to Listing'),
265 );
266 $buttons[] = array(
267 'type' => 'done',
268 'name' => ts('Merge and View Result'),
269 'icon' => 'fa-check-circle',
270 );
271 }
272
273 $buttons[] = array(
274 'type' => 'cancel',
275 'name' => ts('Cancel'),
276 );
277
278 $this->addButtons($buttons);
279 $this->addFormRule(array('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 = array();
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", array(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 = array('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.', array(1 => $name)) . '</li><li>' . ts('Contact ID %1 has been deleted.', array(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));
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.', array(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::singleton()->getLoggedInContactID() == $oid) {
380 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
381 array(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 }