Merge pull request #11250 from agh1/no-update-indices
[civicrm-core.git] / CRM / Contact / Form / Merge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 there'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 /**
55 * String for quickform bug handling.
56 *
57 * FIXME: QuickForm can't create advcheckboxes with value set to 0 or '0' :(
58 * see HTML_QuickForm_advcheckbox::setValues() - but patching that doesn't
59 * help, as QF doesn't put the 0-value elements in exportValues() anyway...
60 * to side-step this, we use the below UUID as a (re)placeholder
61 *
62 * @var string
63 */
64 var $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
65
66 public function preProcess() {
67 try {
68
69 $this->_cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
70 $this->_oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
71 $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
72
73 $this->_rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
74 $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
75 $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
76 $this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
77 $urlParams = "reset=1&rgid={$this->_rgid}&gid={$this->_gid}&limit=" . $this->limit;
78
79 $this->bounceIfInvalid($this->_cid, $this->_oid);
80
81 $this->_contactType = civicrm_api3('Contact', 'getvalue', array(
82 'id' => $this->_cid,
83 'return' => 'contact_type',
84 ));
85
86 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParams . '&action=browse');
87
88 if (!$this->_rgid) {
89 // Unset browse URL as we have come from the search screen.
90 $browseUrl = '';
91 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array(
92 'contact_type' => $this->_contactType,
93 'used' => 'Supervised',
94 'return' => 'id',
95 ));
96 }
97 $this->assign('browseUrl', $browseUrl);
98 if ($browseUrl) {
99 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
100 }
101
102 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid);
103
104 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
105 $where = "de.id IS NULL";
106
107 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
108
109 // get user info of main contact.
110 $config = CRM_Core_Config::singleton();
111 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
112
113 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
114 $mainUser = NULL;
115 if ($mainUfId) {
116 // d6 compatible
117 if ($config->userSystem->is_drupal == '1') {
118 $mainUser = user_load($mainUfId);
119 }
120 elseif ($config->userFramework == 'Joomla') {
121 $mainUser = JFactory::getUser($mainUfId);
122 }
123
124 $this->assign('mainUfId', $mainUfId);
125 $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
126 }
127
128 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
129 "reset=1&action=update&cid={$this->_oid}&oid={$this->_cid}&rgid={$this->_rgid}&gid={$gid}"
130 );
131 if (!$flip) {
132 $flipUrl .= '&flip=1';
133 }
134 $this->assign('flip', $flipUrl);
135
136 $this->prev = $this->next = NULL;
137 foreach (array(
138 'prev',
139 'next',
140 ) as $position) {
141 if (!empty($pos[$position])) {
142 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
143 $urlParams .= "&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
144 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
145 $this->assign($position, $this->$position);
146 }
147 }
148 }
149
150 // get user info of other contact.
151 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_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 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
171 $main = $this->_mainDetails = $rowsElementsAndInfo['main_details'];
172 $other = $this->_otherDetails = $rowsElementsAndInfo['other_details'];
173
174 $this->assign('contact_type', $main['contact_type']);
175 $this->assign('main_name', $main['display_name']);
176 $this->assign('other_name', $other['display_name']);
177 $this->assign('main_cid', $main['contact_id']);
178 $this->assign('other_cid', $other['contact_id']);
179 $this->assign('rgid', $this->_rgid);
180
181 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
182
183 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
184 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
185 $this->assign('rows', $rowsElementsAndInfo['rows']);
186
187 // add elements
188 foreach ($rowsElementsAndInfo['elements'] as $element) {
189 // We could push this down to the getRowsElementsAndInfo function but it's
190 // already so overloaded - let's start moving towards doing form-things
191 // on the form.
192 if (substr($element[1], 0, 13) === 'move_location') {
193 $element[4] = array_merge(
194 (array) CRM_Utils_Array::value(4, $element, array()),
195 array(
196 'data-location' => substr($element[1], 14),
197 'data-is_location' => TRUE,
198 ));
199 }
200 if (substr($element[1], 0, 15) === 'location_blocks') {
201 // @todo We could add some data elements here to make jquery manipulation more straight-forward
202 // @todo consider enabling if it is an add & defaulting to true.
203 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, array()), array('disabled' => TRUE));
204 }
205 $this->addElement($element[0],
206 $element[1],
207 array_key_exists('2', $element) ? $element[2] : NULL,
208 array_key_exists('3', $element) ? $element[3] : NULL,
209 array_key_exists('4', $element) ? $element[4] : NULL,
210 array_key_exists('5', $element) ? $element[5] : NULL
211 );
212 }
213
214 // add related table elements
215 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
216 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
217 $element->setChecked(TRUE);
218 }
219
220 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
221 $this->assign('userContextURL', CRM_Core_Session::singleton()
222 ->readUserContext());
223 }
224 catch (CRM_Core_Exception $e) {
225 CRM_Core_Error::statusBounce(ts($e->getMessage()));
226 }
227 }
228
229 public function addRules() {
230 }
231
232 public function buildQuickForm() {
233 $this->unsavedChangesWarn = FALSE;
234 CRM_Utils_System::setTitle(ts('Merge %1 contacts', array(1 => $this->_contactType)));
235 $buttons = array();
236
237 $buttons[] = array(
238 'type' => 'next',
239 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
240 'isDefault' => TRUE,
241 'icon' => $this->next ? 'circle-triangle-e' : 'check',
242 );
243
244 if ($this->next || $this->prev) {
245 $buttons[] = array(
246 'type' => 'submit',
247 'name' => ts('Merge and go to Listing'),
248 );
249 $buttons[] = array(
250 'type' => 'done',
251 'name' => ts('Merge and View Result'),
252 'icon' => 'fa-check-circle',
253 );
254 }
255
256 $buttons[] = array(
257 'type' => 'cancel',
258 'name' => ts('Cancel'),
259 );
260
261 $this->addButtons($buttons);
262 $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
263 }
264
265 /**
266 * @param $fields
267 * @param $files
268 * @param $self
269 *
270 * @return array
271 */
272 public static function formRule($fields, $files, $self) {
273 $errors = array();
274 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
275 'civicrm/contact/merge',
276 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
277 );
278 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
279 $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));
280 }
281 return $errors;
282 }
283
284 public function postProcess() {
285 $formValues = $this->exportValues();
286
287 $formValues['main_details'] = $this->_mainDetails;
288 $formValues['other_details'] = $this->_otherDetails;
289 $migrationData = array('migration_info' => $formValues);
290 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
291 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
292
293 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
294 $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>';
295 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
296
297 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
298 $urlParams = "reset=1&gid={$this->_gid}&rgid={$this->_rgid}&limit={$this->limit}";
299
300 if (!empty($formValues['_qf_Merge_submit'])) {
301 $urlParams .= "&action=update";
302 $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind',
303 $urlParams
304 );
305 CRM_Utils_System::redirect($lisitingURL);
306 }
307 if (!empty($formValues['_qf_Merge_done'])) {
308 CRM_Utils_System::redirect($url);
309 }
310
311 if ($this->next && $this->_mergeId) {
312 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid);
313
314 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
315 $where = "de.id IS NULL";
316
317 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
318
319 if (!empty($pos) &&
320 $pos['next']['id1'] &&
321 $pos['next']['id2']
322 ) {
323
324 $urlParams .= "&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
325 $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
326 }
327 }
328
329 CRM_Utils_System::redirect($url);
330 }
331
332 /**
333 * Bounce if the merge action is invalid.
334 *
335 * We don't allow the merge if it is nonsensical, marked as a duplicate
336 * or outside the user's permission.
337 *
338 * @param int $cid
339 * Contact ID to retain
340 * @param int $oid
341 * Contact ID to delete.
342 */
343 public function bounceIfInvalid($cid, $oid) {
344 if ($cid == $oid) {
345 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
346 }
347
348 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
349 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'))));
350 }
351
352 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
353 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
354 )
355 ) {
356 CRM_Utils_System::permissionDenied();
357 }
358 // ensure that oid is not the current user, if so refuse to do the merge
359 if (CRM_Core_Session::singleton()->getLoggedInContactID() == $oid) {
360 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
361 array(1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName())
362 );
363 CRM_Core_Error::statusBounce($message);
364 }
365 }
366
367 }