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