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