Merge pull request #7991 from fuzionnz/CRM-16898
[civicrm-core.git] / CRM / Contact / Form / Merge.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33
86538308 34/**
5a409b50 35 * Class CRM_Contact_Form_Merge.
86538308 36 */
6a488035
TO
37class CRM_Contact_Form_Merge extends CRM_Core_Form {
38 // the id of the contact that tere'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
6a488035
TO
47 // FIXME: QuickForm can't create advcheckboxes with value set to 0 or '0' :(
48 // see HTML_QuickForm_advcheckbox::setValues() - but patching that doesn't
49 // help, as QF doesn't put the 0-value elements in exportValues() anyway...
50 // to side-step this, we use the below UUID as a (re)placeholder
8ef12e64 51 var $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
52
00be9182 53 public function preProcess() {
6a488035
TO
54 if (!CRM_Core_Permission::check('merge duplicate contacts')) {
55 CRM_Core_Error::fatal(ts('You do not have access to this page'));
56 }
57
58 $rows = array();
353ffa53
TO
59 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
60 $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
6a488035
TO
61 $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
62
353ffa53
TO
63 $this->_rgid = $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
64 $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
6a488035
TO
65 $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
66
6d5a3f21
CW
67 // Sanity check
68 if ($cid == $oid) {
69 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
70 }
71
6a488035 72 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
cce70162 73 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'))));
6a488035
TO
74 }
75
2ae26001 76 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid);
77
78 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
6a488035
TO
79 $where = "de.id IS NULL";
80
81 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
82
83 // Block access if user does not have EDIT permissions for both contacts.
84 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
353ffa53
TO
85 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
86 )
87 ) {
6a488035
TO
88 CRM_Utils_System::permissionDenied();
89 }
90
91 // get user info of main contact.
92 $config = CRM_Core_Config::singleton();
93 $config->doNotResetCache = 1;
94
95 $viewUser = CRM_Core_Permission::check('access user profiles');
96 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
97 $mainUser = NULL;
98 if ($mainUfId) {
99 // d6 compatible
100 if ($config->userSystem->is_drupal == '1') {
101 $mainUser = user_load($mainUfId);
102 }
103 elseif ($config->userFramework == 'Joomla') {
104 $mainUser = JFactory::getUser($mainUfId);
105 }
106
107 $this->assign('mainUfId', $mainUfId);
108 $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
109 }
110
395d8dc6 111 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
6a488035
TO
112 "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$rgid}&gid={$gid}"
113 );
114 if (!$flip) {
115 $flipUrl .= '&flip=1';
116 }
117 $this->assign('flip', $flipUrl);
118
119 $this->prev = $this->next = NULL;
120 foreach (array(
353ffa53 121 'prev',
389bcebf 122 'next',
353ffa53 123 ) as $position) {
6a488035
TO
124 if (!empty($pos[$position])) {
125 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
126 $urlParam = "reset=1&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
127
128 if ($rgid) {
129 $urlParam .= "&rgid={$rgid}";
130 }
131 if ($gid) {
132 $urlParam .= "&gid={$gid}";
133 }
134
395d8dc6 135 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
6a488035
TO
136 $this->assign($position, $this->$position);
137 }
138 }
139 }
140
141 // get user info of other contact.
142 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
143 $otherUser = NULL;
144
145 if ($otherUfId) {
146 // d6 compatible
147 if ($config->userSystem->is_drupal == '1') {
148 $otherUser = user_load($otherUfId);
149 }
150 elseif ($config->userFramework == 'Joomla') {
151 $otherUser = JFactory::getUser($otherUfId);
152 }
153
154 $this->assign('otherUfId', $otherUfId);
155 $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
156 }
157
158 $cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
159 $this->assign('user', $cmsUser);
160
161 $session = CRM_Core_Session::singleton();
162
163 // context fixed.
164 if ($rgid) {
165 $urlParam = "reset=1&action=browse&rgid={$rgid}";
166 if ($gid) {
167 $urlParam .= "&gid={$gid}";
168 }
395d8dc6 169 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParam));
6a488035
TO
170 }
171
172 // ensure that oid is not the current user, if so refuse to do the merge
173 if ($session->get('userID') == $oid) {
174 $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
175 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
176 array(1 => $display_name)
177 );
178 CRM_Core_Error::statusBounce($message);
179 }
180
181 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($cid, $oid);
471ec338
BS
182 $main = $this->_mainDetails = &$rowsElementsAndInfo['main_details'];
183 $other = $this->_otherDetails = &$rowsElementsAndInfo['other_details'];
6a488035
TO
184
185 if ($main['contact_id'] != $cid) {
186 CRM_Core_Error::fatal(ts('The main contact record does not exist'));
187 }
188
189 if ($other['contact_id'] != $oid) {
190 CRM_Core_Error::fatal(ts('The other contact record does not exist'));
191 }
192
6a488035 193 $this->assign('contact_type', $main['contact_type']);
6a488035
TO
194 $this->assign('main_name', $main['display_name']);
195 $this->assign('other_name', $other['display_name']);
196 $this->assign('main_cid', $main['contact_id']);
197 $this->assign('other_cid', $other['contact_id']);
00c461ec 198 $this->assign('rgid', $rgid);
6a488035 199
353ffa53
TO
200 $this->_cid = $cid;
201 $this->_oid = $oid;
202 $this->_rgid = $rgid;
6a488035 203 $this->_contactType = $main['contact_type'];
d664f648 204 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
6a488035 205
bf43eaac
J
206 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
207 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
6a488035
TO
208 $this->assign('rows', $rowsElementsAndInfo['rows']);
209
6a488035
TO
210 // add elements
211 foreach ($rowsElementsAndInfo['elements'] as $element) {
212 $this->addElement($element[0],
213 $element[1],
214 array_key_exists('2', $element) ? $element[2] : NULL,
215 array_key_exists('3', $element) ? $element[3] : NULL,
216 array_key_exists('4', $element) ? $element[4] : NULL,
217 array_key_exists('5', $element) ? $element[5] : NULL
218 );
219 }
220
221 // add related table elements
222 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
223 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
224 $element->setChecked(TRUE);
225 }
226
227 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
228 $this->assign('userContextURL', $session->readUserContext());
229 }
230
86538308
EM
231 /**
232 * This virtual function is used to set the default values of
233 * various form elements
234 *
235 * access public
236 *
a6c01b45
CW
237 * @return array
238 * reference to the array of default values
86538308
EM
239 */
240 /**
241 * @return array
242 */
00be9182 243 public function setDefaultValues() {
6a488035
TO
244 return array('deleteOther' => 1);
245 }
246
6ea503d4
TO
247 public function addRules() {
248 }
6a488035
TO
249
250 public function buildQuickForm() {
d5be719d 251 CRM_Utils_System::setTitle(ts('Merge %1 contacts', array(1 => $this->_contactType)));
fd66df85
CW
252 $buttons = array();
253
254 $buttons[] = array(
255 'type' => 'next',
3709190a 256 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
fd66df85
CW
257 'isDefault' => TRUE,
258 'icon' => $this->next ? 'circle-triangle-e' : 'check',
259 );
6a488035
TO
260
261 if ($this->next || $this->prev) {
fd66df85
CW
262 $buttons[] = array(
263 'type' => 'submit',
3709190a 264 'name' => ts('Merge and go to Listing'),
6a488035 265 );
fd66df85
CW
266 $buttons[] = array(
267 'type' => 'done',
268 'name' => ts('Merge and View Result'),
0291a521 269 'icon' => 'fa-check-circle',
6a488035
TO
270 );
271 }
272
fd66df85
CW
273 $buttons[] = array(
274 'type' => 'cancel',
275 'name' => ts('Cancel'),
276 );
277
278 $this->addButtons($buttons);
4b87bd02 279 $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
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) {
4b87bd02 290 $errors = array();
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)) {
0653585f 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));
4b87bd02 297 }
298 return $errors;
6a488035
TO
299 }
300
301 public function postProcess() {
302 $formValues = $this->exportValues();
8ef12e64 303
6a488035
TO
304 // reset all selected contact ids from session
305 // when we came from search context, CRM-3526
306 $session = CRM_Core_Session::singleton();
307 if ($session->get('selectedSearchContactIds')) {
308 $session->resetScope('selectedSearchContactIds');
309 }
310
471ec338
BS
311 $formValues['main_details'] = $this->_mainDetails;
312 $formValues['other_details'] = $this->_otherDetails;
6a488035
TO
313
314 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $formValues);
315
7b99ead3
CW
316 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
317 $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>';
318 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
319
6a488035 320 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
a7488080 321 if (!empty($formValues['_qf_Merge_submit'])) {
6a488035
TO
322 $listParamsURL = "reset=1&action=update&rgid={$this->_rgid}";
323 if ($this->_gid) {
324 $listParamsURL .= "&gid={$this->_gid}";
325 }
326 $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind',
327 $listParamsURL
328 );
329 CRM_Utils_System::redirect($lisitingURL);
330 }
353ffa53 331 if (!empty($formValues['_qf_Merge_done'])) {
6a488035
TO
332 CRM_Utils_System::redirect($url);
333 }
334
335 if ($this->next && $this->_mergeId) {
2ae26001 336 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid);
6a488035 337
2ae26001 338 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
6a488035
TO
339 $where = "de.id IS NULL";
340
341 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
342
343 if (!empty($pos) &&
344 $pos['next']['id1'] &&
345 $pos['next']['id2']
346 ) {
347
348 $urlParam = "reset=1&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
349 if ($this->_rgid) {
350 $urlParam .= "&rgid={$this->_rgid}";
351 }
352 if ($this->_gid) {
353 $urlParam .= "&gid={$this->_gid}";
354 }
355
395d8dc6 356 $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
6a488035
TO
357 }
358 }
359
360 CRM_Utils_System::redirect($url);
361 }
96025800 362
6a488035 363}