Merge pull request #8599 from PalanteJon/CRM-18980
[civicrm-core.git] / CRM / Contact / Form / Merge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 /**
48 * Query limit to be retained in the urls.
49 *
50 * @var int
51 */
52 var $limit;
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
58 var $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
59
60 public 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 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
66 $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
67 $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
68
69 $this->_rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
70 $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
71 $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
72 $this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
73 $urlParams = "reset=1&rgid={$this->_rgid}&gid={$this->_gid}&limit=" . $this->limit;
74
75 // Sanity check
76 if ($cid == $oid) {
77 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
78 }
79
80 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
81 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'))));
82 }
83 $this->_contactType = civicrm_api3('Contact', 'getvalue', array('id' => $cid, 'return' => 'contact_type'));
84 $isFromDedupeScreen = TRUE;
85 if (!$this->_rgid) {
86 $isFromDedupeScreen = FALSE;
87 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array(
88 'contact_type' => $this->_contactType,
89 'used' => 'Supervised',
90 'return' => 'id',
91 ));
92 }
93
94 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid);
95
96 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
97 $where = "de.id IS NULL";
98
99 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $cid, $oid, $this->_mergeId, $join, $where, $flip);
100
101 // Block access if user does not have EDIT permissions for both contacts.
102 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
103 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
104 )
105 ) {
106 CRM_Utils_System::permissionDenied();
107 }
108
109 // get user info of main contact.
110 $config = CRM_Core_Config::singleton();
111 $config->doNotResetCache = 1;
112
113 $viewUser = CRM_Core_Permission::check('access user profiles');
114 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($cid);
115 $mainUser = NULL;
116 if ($mainUfId) {
117 // d6 compatible
118 if ($config->userSystem->is_drupal == '1') {
119 $mainUser = user_load($mainUfId);
120 }
121 elseif ($config->userFramework == 'Joomla') {
122 $mainUser = JFactory::getUser($mainUfId);
123 }
124
125 $this->assign('mainUfId', $mainUfId);
126 $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
127 }
128
129 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
130 "reset=1&action=update&cid={$oid}&oid={$cid}&rgid={$this->_rgid}&gid={$gid}"
131 );
132 if (!$flip) {
133 $flipUrl .= '&flip=1';
134 }
135 $this->assign('flip', $flipUrl);
136
137 $this->prev = $this->next = NULL;
138 foreach (array(
139 'prev',
140 'next',
141 ) as $position) {
142 if (!empty($pos[$position])) {
143 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
144 $urlParams .= "&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
145 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
146 $this->assign($position, $this->$position);
147 }
148 }
149 }
150
151 // get user info of other contact.
152 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($oid);
153 $otherUser = NULL;
154
155 if ($otherUfId) {
156 // d6 compatible
157 if ($config->userSystem->is_drupal == '1') {
158 $otherUser = user_load($otherUfId);
159 }
160 elseif ($config->userFramework == 'Joomla') {
161 $otherUser = JFactory::getUser($otherUfId);
162 }
163
164 $this->assign('otherUfId', $otherUfId);
165 $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
166 }
167
168 $cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
169 $this->assign('user', $cmsUser);
170
171 $session = CRM_Core_Session::singleton();
172
173 // context fixed.
174 if ($isFromDedupeScreen) {
175 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParams . '&action=browse');
176 $session->pushUserContext($browseUrl);
177 }
178 $this->assign('browseUrl', empty($browseUrl) ? '' : $browseUrl);
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', $this->_rgid);
207
208 $this->_cid = $cid;
209 $this->_oid = $oid;
210
211 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
212
213 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
214 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
215 $this->assign('rows', $rowsElementsAndInfo['rows']);
216
217 // add elements
218 foreach ($rowsElementsAndInfo['elements'] as $element) {
219 $this->addElement($element[0],
220 $element[1],
221 array_key_exists('2', $element) ? $element[2] : NULL,
222 array_key_exists('3', $element) ? $element[3] : NULL,
223 array_key_exists('4', $element) ? $element[4] : NULL,
224 array_key_exists('5', $element) ? $element[5] : NULL
225 );
226 }
227
228 // add related table elements
229 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
230 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
231 $element->setChecked(TRUE);
232 }
233
234 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
235 $this->assign('userContextURL', $session->readUserContext());
236 }
237
238 /**
239 * This virtual function is used to set the default values of
240 * various form elements
241 *
242 * access public
243 *
244 * @return array
245 * reference to the array of default values
246 */
247 /**
248 * @return array
249 */
250 public function setDefaultValues() {
251 return array('deleteOther' => 1);
252 }
253
254 public function addRules() {
255 }
256
257 public function buildQuickForm() {
258 CRM_Utils_System::setTitle(ts('Merge %1 contacts', array(1 => $this->_contactType)));
259 $buttons = array();
260
261 $buttons[] = array(
262 'type' => 'next',
263 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
264 'isDefault' => TRUE,
265 'icon' => $this->next ? 'circle-triangle-e' : 'check',
266 );
267
268 if ($this->next || $this->prev) {
269 $buttons[] = array(
270 'type' => 'submit',
271 'name' => ts('Merge and go to Listing'),
272 );
273 $buttons[] = array(
274 'type' => 'done',
275 'name' => ts('Merge and View Result'),
276 'icon' => 'fa-check-circle',
277 );
278 }
279
280 $buttons[] = array(
281 'type' => 'cancel',
282 'name' => ts('Cancel'),
283 );
284
285 $this->addButtons($buttons);
286 $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
287 }
288
289 /**
290 * @param $fields
291 * @param $files
292 * @param $self
293 *
294 * @return array
295 */
296 public static function formRule($fields, $files, $self) {
297 $errors = array();
298 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
299 'civicrm/contact/merge',
300 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
301 );
302 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
303 $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));
304 }
305 return $errors;
306 }
307
308 public function postProcess() {
309 $formValues = $this->exportValues();
310
311 // reset all selected contact ids from session
312 // when we came from search context, CRM-3526
313 $session = CRM_Core_Session::singleton();
314 if ($session->get('selectedSearchContactIds')) {
315 $session->resetScope('selectedSearchContactIds');
316 }
317
318 $formValues['main_details'] = $this->_mainDetails;
319 $formValues['other_details'] = $this->_otherDetails;
320 $migrationData = array('migration_info' => $formValues);
321 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
322 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
323
324 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
325 $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>';
326 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
327
328 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
329 $urlParams = "reset=1&gid={$this->_gid}&rgid={$this->_rgid}&limit={$this->limit}";
330
331 if (!empty($formValues['_qf_Merge_submit'])) {
332 $urlParams .= "&action=update";
333 $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind',
334 $urlParams
335 );
336 CRM_Utils_System::redirect($lisitingURL);
337 }
338 if (!empty($formValues['_qf_Merge_done'])) {
339 CRM_Utils_System::redirect($url);
340 }
341
342 if ($this->next && $this->_mergeId) {
343 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid);
344
345 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
346 $where = "de.id IS NULL";
347
348 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
349
350 if (!empty($pos) &&
351 $pos['next']['id1'] &&
352 $pos['next']['id2']
353 ) {
354
355 $urlParams .= "&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
356 $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
357 }
358 }
359
360 CRM_Utils_System::redirect($url);
361 }
362
363 }