Merge pull request #3179 from webpartners/master
[civicrm-core.git] / CRM / Contact / Form / Merge.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
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
6a488035
TO
60 function preProcess() {
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
74 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
75 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'))));
76 }
77
78 //load cache mechanism
79 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'contact_type');
80 $cacheKey = "merge $contactType";
81 $cacheKey .= $rgid ? "_{$rgid}" : '_0';
82 $cacheKey .= $gid ? "_{$gid}" : '_0';
83
8ef12e64 84 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
6a488035
TO
85 pn.entity_id2 = de.contact_id2 )";
86 $where = "de.id IS NULL";
87
88 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
89
90 // Block access if user does not have EDIT permissions for both contacts.
91 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
92 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
93 )) {
94 CRM_Utils_System::permissionDenied();
95 }
96
97 // get user info of main contact.
98 $config = CRM_Core_Config::singleton();
99 $config->doNotResetCache = 1;
100
101 $viewUser = CRM_Core_Permission::check('access user profiles');
102 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
103 $mainUser = NULL;
104 if ($mainUfId) {
105 // d6 compatible
106 if ($config->userSystem->is_drupal == '1') {
107 $mainUser = user_load($mainUfId);
108 }
109 elseif ($config->userFramework == 'Joomla') {
110 $mainUser = JFactory::getUser($mainUfId);
111 }
112
113 $this->assign('mainUfId', $mainUfId);
114 $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
115 }
116
395d8dc6 117 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
6a488035
TO
118 "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$rgid}&gid={$gid}"
119 );
120 if (!$flip) {
121 $flipUrl .= '&flip=1';
122 }
123 $this->assign('flip', $flipUrl);
124
125 $this->prev = $this->next = NULL;
126 foreach (array(
127 'prev', 'next') as $position) {
128 if (!empty($pos[$position])) {
129 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
130 $urlParam = "reset=1&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
131
132 if ($rgid) {
133 $urlParam .= "&rgid={$rgid}";
134 }
135 if ($gid) {
136 $urlParam .= "&gid={$gid}";
137 }
138
395d8dc6 139 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
6a488035
TO
140 $this->assign($position, $this->$position);
141 }
142 }
143 }
144
145 // get user info of other contact.
146 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
147 $otherUser = NULL;
148
149 if ($otherUfId) {
150 // d6 compatible
151 if ($config->userSystem->is_drupal == '1') {
152 $otherUser = user_load($otherUfId);
153 }
154 elseif ($config->userFramework == 'Joomla') {
155 $otherUser = JFactory::getUser($otherUfId);
156 }
157
158 $this->assign('otherUfId', $otherUfId);
159 $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
160 }
161
162 $cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
163 $this->assign('user', $cmsUser);
164
165 $session = CRM_Core_Session::singleton();
166
167 // context fixed.
168 if ($rgid) {
169 $urlParam = "reset=1&action=browse&rgid={$rgid}";
170 if ($gid) {
171 $urlParam .= "&gid={$gid}";
172 }
395d8dc6 173 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParam));
6a488035
TO
174 }
175
176 // ensure that oid is not the current user, if so refuse to do the merge
177 if ($session->get('userID') == $oid) {
178 $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name');
179 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
180 array(1 => $display_name)
181 );
182 CRM_Core_Error::statusBounce($message);
183 }
184
185 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($cid, $oid);
471ec338
BS
186 $main = $this->_mainDetails = &$rowsElementsAndInfo['main_details'];
187 $other = $this->_otherDetails = &$rowsElementsAndInfo['other_details'];
6a488035
TO
188
189 if ($main['contact_id'] != $cid) {
190 CRM_Core_Error::fatal(ts('The main contact record does not exist'));
191 }
192
193 if ($other['contact_id'] != $oid) {
194 CRM_Core_Error::fatal(ts('The other contact record does not exist'));
195 }
196
197 $subtypes = CRM_Contact_BAO_ContactType::subTypePairs(NULL, TRUE, '');
198
199 $this->assign('contact_type', $main['contact_type']);
0f6fa7a8 200 if (!empty($main['contact_sub_type'])) {
6a488035
TO
201 $this->assign('main_contact_subtype',
202 CRM_Utils_Array::value('contact_sub_type', $subtypes[$main['contact_sub_type'][0]])
203 );
204 }
0f6fa7a8 205 if (!empty($other['contact_sub_type'])) {
6a488035
TO
206 $this->assign('other_contact_subtype',
207 CRM_Utils_Array::value('contact_sub_type', $subtypes[$other['contact_sub_type'][0]])
208 );
209 }
210 $this->assign('main_name', $main['display_name']);
211 $this->assign('other_name', $other['display_name']);
212 $this->assign('main_cid', $main['contact_id']);
213 $this->assign('other_cid', $other['contact_id']);
00c461ec 214 $this->assign('rgid', $rgid);
6a488035
TO
215
216 $this->_cid = $cid;
217 $this->_oid = $oid;
218 $this->_rgid = $rgid;
219 $this->_contactType = $main['contact_type'];
d664f648 220 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
6a488035
TO
221
222 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_loc_block']));
223 $this->assign('rows', $rowsElementsAndInfo['rows']);
224
225 $this->_locBlockIds = array(
226 'main' => $rowsElementsAndInfo['main_details']['loc_block_ids'],
227 'other' => $rowsElementsAndInfo['other_details']['loc_block_ids']
228 );
229
230 // add elements
231 foreach ($rowsElementsAndInfo['elements'] as $element) {
232 $this->addElement($element[0],
233 $element[1],
234 array_key_exists('2', $element) ? $element[2] : NULL,
235 array_key_exists('3', $element) ? $element[3] : NULL,
236 array_key_exists('4', $element) ? $element[4] : NULL,
237 array_key_exists('5', $element) ? $element[5] : NULL
238 );
239 }
240
241 // add related table elements
242 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
243 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
244 $element->setChecked(TRUE);
245 }
246
247 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
248 $this->assign('userContextURL', $session->readUserContext());
249 }
250
86538308
EM
251 /**
252 * This virtual function is used to set the default values of
253 * various form elements
254 *
255 * access public
256 *
257 * @return array reference to the array of default values
258 *
259 */
260 /**
261 * @return array
262 */
6a488035
TO
263 function setDefaultValues() {
264 return array('deleteOther' => 1);
265 }
266
267 function addRules() {}
268
269 public function buildQuickForm() {
270 CRM_Utils_System::setTitle(ts('Merge %1s', array(1 => $this->_contactType)));
271 $name = ts('Merge');
272 if ($this->next) {
273 $name = ts('Merge and Goto Next Pair');
274 }
275
276 if ($this->next || $this->prev) {
277 $button = array(
278 array(
279 'type' => 'next',
280 'name' => $name,
281 'isDefault' => TRUE,
282 ),
283 array(
284 'type' => 'submit',
285 'name' => ts('Merge and Goto Listing'),
286 ),
287 array(
288 'type' => 'done',
289 'name' => ts('Merge and View Result'),
290 ),
291 array(
292 'type' => 'cancel',
293 'name' => ts('Cancel'),
294 ),
295 );
296 }
297 else {
298 $button = array(
299 array(
300 'type' => 'next',
301 'name' => $name,
302 'isDefault' => TRUE,
303 ),
304 array(
305 'type' => 'cancel',
306 'name' => ts('Cancel'),
307 ),
308 );
309 }
310
311 $this->addButtons($button);
4b87bd02 312 $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
313 }
314
86538308
EM
315 /**
316 * @param $fields
317 * @param $files
318 * @param $self
319 *
320 * @return array
321 */
4b87bd02 322 static function formRule($fields, $files, $self) {
323 $errors = array();
0653585f 324 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
b74201e4 325 'civicrm/contact/merge',
326 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
327 );
4b87bd02 328 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
0653585f 329 $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 330 }
331 return $errors;
6a488035
TO
332 }
333
334 public function postProcess() {
335 $formValues = $this->exportValues();
8ef12e64 336
6a488035
TO
337 // reset all selected contact ids from session
338 // when we came from search context, CRM-3526
339 $session = CRM_Core_Session::singleton();
340 if ($session->get('selectedSearchContactIds')) {
341 $session->resetScope('selectedSearchContactIds');
342 }
343
471ec338
BS
344 $formValues['main_details'] = $this->_mainDetails;
345 $formValues['other_details'] = $this->_otherDetails;
6a488035
TO
346
347 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $formValues);
348
349 CRM_Core_Session::setStatus(ts('Contact id %1 has been updated and contact id %2 has been deleted.', array(1 => $this->_cid, 2 => $this->_oid)), ts('Contacts Merged'), 'success');
350 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
a7488080 351 if (!empty($formValues['_qf_Merge_submit'])) {
6a488035
TO
352 $listParamsURL = "reset=1&action=update&rgid={$this->_rgid}";
353 if ($this->_gid) {
354 $listParamsURL .= "&gid={$this->_gid}";
355 }
356 $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind',
357 $listParamsURL
358 );
359 CRM_Utils_System::redirect($lisitingURL);
360 }
a7488080 361 if (!empty($formValues['_qf_Merge_done'])) {
6a488035
TO
362 CRM_Utils_System::redirect($url);
363 }
364
365 if ($this->next && $this->_mergeId) {
366 $cacheKey = "merge {$this->_contactType}";
367 $cacheKey .= $this->_rgid ? "_{$this->_rgid}" : '_0';
368 $cacheKey .= $this->_gid ? "_{$this->_gid}" : '_0';
369
8ef12e64 370 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
6a488035
TO
371 pn.entity_id2 = de.contact_id2 )";
372 $where = "de.id IS NULL";
373
374 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
375
376 if (!empty($pos) &&
377 $pos['next']['id1'] &&
378 $pos['next']['id2']
379 ) {
380
381 $urlParam = "reset=1&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
382 if ($this->_rgid) {
383 $urlParam .= "&rgid={$this->_rgid}";
384 }
385 if ($this->_gid) {
386 $urlParam .= "&gid={$this->_gid}";
387 }
388
395d8dc6 389 $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParam);
6a488035
TO
390 }
391 }
392
393 CRM_Utils_System::redirect($url);
394 }
395}
396